函数模板:typename声明

Function Template: typename declaration

本文关键字:声明 typename 函数模板      更新时间:2023-10-16

在GCC上,下面给我一个错误:no type named 'x' in 'struct Type'

在VC++上,它抱怨p是未声明的

struct Type
{
   static int const x = 0;
};
template <class T> void Func()
{
   typename T::x * p; // p to be pointer
}
int main()
{
   Func<Type>();
}

T::x变为Type::x,它是int,而不是类型。

您已经告诉编译器T::x通过使用typename来命名类型。实例化Func<Type>时,T::x不是类型,因此编译器会报告错误。

由于Type::x不是类型,而是。因此,当您编写typename时,您会告诉编译器在Type中找到一个名为x的嵌套但它做不到。因此GCC说no type named 'x' in 'struct Type',这比VC++生成的消息更有帮助。

在C++11中,using关键字可以用于类型别名

struct Type
{
    using x = static int const;
};