C++0x的template alias以及using

2014-11-24 12:55:07 · 作者: · 浏览: 1

typedef template用于将一个较抽象的template "alias" 成一个较具体的 template。大体上是这样:

template
class A
{
private:
T a;
};

如果T本身也可以是template的,那么你很可能想到这样:

template
typedef A > B;

这里面一个A template被具体化到其一个成员的template,遗憾的是,上述语法在 C++里面是非法的。C++0x(2.0)用using关键字提供了上述支持,大体上是这样:

template< typename First, typename Second, int third>
class SomeType;

template< typename Second>
using TypedefName = SomeType;

详见: http://en.wikipedia.org/wiki/C%2B%2B0x#Template_aliases

另外,using还可以用来publish基类的protected方法:

class Base:
{
protected:
void Method();
};

class D:public Base
{
public:
using Base::Method;
};

在某些实现中(据说是vc),直接在子类里面public声明基类的protected方法就能起到publish的作用,但是合乎标准的做法如上。这个我孤陋寡闻,以前居然也没注意到。