C++ templete: "class" vs "typename" in a template-parameter

C++03标准说,class和typename没有啥区别:There is no semantic difference between class and typename in a template-parameter

Stan Lippman在他的博客[Ref StanL]中这么说. 这是一个历史遗留问题。最初,Stroustrup也许为了不破坏已经存在的代码,所以重用了class这个已有的关键字。
但毫无疑问class这个关键字很迷惑人,会让初学者觉得在template里只能使用class,而不能使用其他built-in type. 并且在ISO C++标准化过程中,在模板的定义中存在一个异议。
template <class T>
class Demonstration {
public:
void method() {
    T::A *aObj; // oops … <==what's this??
     // …
};

这里的目的是申明了一个T::A*类型的局部变量aObj,但是编译器的语法会认为这里是T中的static变量T::A乘以aObj.
于是标准委员会决定增加了一个新的关键字,typename. 他的意思就如他的名字,非常直白。就像这样
typename T::A* a6; // declare pointer to T’s A
Scott Myers在Effective C++(3rd ed.)的第42条说, class和typename在申明一个模板的类型参数的时候,没有区别。
template<class T> class Widget;                 // uses "class"
template<typename T> class Widget;              // uses "typename"

但是在指明模板的嵌套类型的时候,只能用typename, 就比如
template <class T>
class Dem{
public:
      void foo()  {
            typename T::A * aObj;
      }
};

在显式的实例化一个模板的时候,只能用class
template class Foo<int>;
[Ref StanL]Why C++ Supports both Class and Typename for Type Parameters(http://blogs.msdn.com/b/slippman/archive/2004/08/11/212768.aspx)


posted @ 2011-07-02 15:20  嗷嗷  阅读(778)  评论(0编辑  收藏  举报