Type Alias & using

文章目录
  1. 1. Type alias
  2. 2. using

Type alias

Similar to typedef

1
2
3
4
5
6
7
8
9
10
11
// type alias, identical to
// typedef void (*func)(int, int)

using func = void (*)(int, int);

void example(int, int) {}
func fn = example;

// alias template
template<class CharT> using mystring = std::basic_string<CharT, std::char_traits<CharT>>;
mystring<char> str;

和 <string_fwd.h> 都有以下 typedef:

typedef basic_string string;

1
2
3
4
5
6
7
8
9
10
// type alias can introduce a member typedef name
template<typename T>
struct Container {
using value_type = T; // typedef T value_type;
};

template<typename Cntr>
void fn2(const Cntr& c) {
typename Cntr::value_type n;
}

using

  1. using-directives for namespaces and using-declarations for namespace members;

    1
    2
    using namespace std;
    using std::count;
  2. using-declarations for class members

    1
    2
    3
    4
    5
    protected:
    using _Base::_M_allocate;
    using _Base::_M_deallocate;
    using _Base::_S_nword;
    using _Base::_M_get_Bit_allocator;
  3. type alias and alias template declaration