typename

维基百科,自由的百科全书

typename是一个C++程序设计语言中的关键字。当用于泛型编程时是另一术语"class"的同义词。在第一版 ISO 标准完成之前的原始 C++ 编译器中,typename关键字还不是 C++ 语言的一部分,当时Bjarne Stroustrup使用class关键字作为模板参数。现在typename是首选关键字,但较旧的源代码可能仍会看到使用class关键字(例如,参见 Bjarne Stroustrup 于 1994 年出版的《The Design and Evolution of C++》与 Bjarne Stroustrup 于 2013 年出版的《The C++ Programming Language: Four Edition》中的源代码示例之间的差异)。这个关键字用于指出模板声明(或定义)中的非独立名称(dependent names)是类型名,而非变量名。以下是对于泛型编程typename两种迥然不同的用法的解释。

class关键字的同义词[编辑]

这是一项C++编程语言的泛型编程(或曰“模板编程”)的功能,typename关键字用于引入一个模板参数,例如:

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

这种情况下,typename可用另一个等效的关键字class代替,如下代码片段所示:

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

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

类型名指示符[编辑]

考虑下面的错误代码:

template <typename 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到底是不是“模板参数的非独立名字”,简称“非独立名字”(dependent name)。注意,任何含有名为“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会被解释为T::bar乘以p(但p无处可寻),而不是声明p为指向T::bar类型的对象的指针。 实际上,就算StructWithBarAsType里定义了bar是int类型也没用,因为在编译foo()时,编译器还没看到StructWithBarAsType。 如果还有另一个名为StructWithBarAsValue的类,如下:

struct StructWithBarAsValue {
    int bar;
};

那么,编译器就会把foo()里的

T::bar * p

翻译成访问StructWithBarAsValue::bar这个成员数据,但是StructWithBarAsValue里的bar并非静态成员数据,所以还是会报错。

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

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

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

参考文献[编辑]