C++11中using关键字的主要作用是:为一个模板库定义一个别名。
下面列举出using的几种用法:
/*定义别名*/
template<class T>
using Tlist = std::list<T>;
using Tlist = std::list<char>;
Tlist listChar;
//typedef void(*df)();
using df = void(*)();
/*使用外部构造*/
using A::A;
/*引用外部类型*/
using typename A;
1、用法一:引用命名空间
using namespace std;
2、用法二:alias的使用
using 还可以指定别名,比如using SO3d = SO3<double>; 那么它和typedef ,有什么区别?
可读性
我们使用typedef定义函数指针:typedef void (* FUN_) (int, int); 函数指针指向的函数返回值是void,输入参数是int, int型。
我们使用using 定义函数指针:using FUN_ = void(*)(int, int);
using的写法把别名的名字强制分离到了左边,而把别名指向的放在了右边,比较清晰
此外,using可以指定模板的别名,而typedef不行
/*假如我们定义一个类模板:*/
template<class _scale, int option>
class Person
{
public:
_scale age;
_scale name[option];
};
template<class _T>
using myperson = Person<_T, 6>; // Ok
//typedef Person<_T, 6> myperson; // fail
myperson<int> p;
3、用法三:子类引用基类成员
假如子类私有继承父类,子类无法使用父类的成员(变量,函数等),但是使用using可以访问,code如下:
template<class _scale, int option>
class Person
{
public:
_scale age;
_scale height;
_scale name[option];
void myprint(void)
{
cout << "age" << age << endl;
}
};
template<class _scale, int option>
class HeighPerson : private Person<_scale, option>
{
public:
using Person<_scale, option>::age; // 使用using 之后变成public
using Person<_scale, option>::myprint; // 使用using, myprint之后变成public
protected:
using Person<_scale, option>::height; //在本来不可访问的,使用using 之后变成protected
void test(void)
{
cout << "age" << age << endl;
}
};
注:此时也只可通过using访问基类的public、protected成员,private成员依旧不可访问;