C++中class和typename的区别

由于历史原因,以前是用class,后来C++ Standard 出现后,引入了typename, 所以他们基本上是一样的,但也有区别。

例1:

// 定义一个返回参数中较大者的通用函数
template <typename T>
const T& max(const T& x, const T& y)
{
  return x > y ? x : y;
}

这种情况下,typename可用关键字class代替,如下代码片段所示:

// 定义一个返回参数中较大者的通用函数
template <class T>
const T& max(const T& x, const T& y)
{
  return x > y ? x : y;
}

以上两段代码没有功能上的区别。

例2:

template <class T>
void foo(const T& t)
{
    // 声明一个指向某个类型为T::bar的对象的指针
    T::bar * p;
}
 
struct StructWithBarAsType
{
    typedef int bar;
}; 
 
int main()
{
    StructWithBarAsType x;
    foo(x);
}

这段代码看起来能通过编译,但是事实上这段代码并不正确。因为编译器并不知道T::bar究竟是一个类型的名字还是一个某个变量的名字。究其根本,造成这种歧义的原因在于,编译器不明白T::bar到底是不是“模板参数的非独立名字”,简称“非独立名字”。注意,任何含有名为“bar”的项的类T,都可以被当作模板参数传入foo()函数,包括typedef类型、枚举类型或者变量等。

为了消除歧义,C++语言标准规定:

A name used in a template declaration or definition and that is dependent on a template-parameter is assumed not to name a type unless the applicable name lookup finds a type name or the name is qualified by the keyword typename.

意即出现上述歧义时,编译器将自动默认bar为一个变量名,而不是类型名。所以上面例子中的代码 T::bar * p 会被解释为乘法,而不是声明p为指向T::bar类型的对象的指针。

如果还有另一个名为StructWithBarAsValue类型,如下:

struct StructWithBarAsValue
{
    int bar;
};

那么,编译器将以完全不同的方式来解释 T::bar * p 的含义。

解决问题的最终办法,就是显式地告诉编译器,T::bar是一个类型名。这就必须用typename关键字,例如:

template <typename T>
void foo(const T& t)
{   
    // 声明一个指向某个类型为T::bar的对象的指针
    typename T::bar * p;
}

这样,编译器就确定了T::bar是一个类型名,p也就自然地被解释为指向T::bar类型的对象的指针了。

例3:当 T 是一个类,而这个类又有子类(假设名为 innerClass) 时,应该用typename

typename T::innerClass   myInnerObject;

typename 告诉编译器,T::innerClass 是一个类,程序要声明一个 T::innerClass 类的对象,而不是声明 T 的静态成员, typename 如果换成 class 则语法错误。

参考文章:https://blogs.msdn.microsoft.com/slippman/2004/08/11/why-c-supports-both-class-and-typename-for-type-parameters/

原文地址:https://www.cnblogs.com/a3192048/p/12241324.html