键入名称应该在 C++ 中常量之前还是之后

Should typename be before or after const in C++?

本文关键字:常量 之后 C++      更新时间:2023-10-16

>我应该写:

template<class T> class Foo {
    typename const T* x;
};

或:

template<class T> class Foo {
    const typename T* x;
};

typename需要与您尝试获取的类型一起使用。 例如,如果您有

template <typename T>
void foo(T& t)
{
    typename const T::iterator bar = t.begin();
}
int main()
{
    std::vector<int> bar{1,2,3}
    foo(bar);
}

您将收到一个编译器错误,用于typename const T::const_iterator bar = t.begin();

,如下所示

"const"之前的预期嵌套名称说明符

其中作为

const typename T::iterator bar = t.begin();

工作得很好。


有关何时、何地以及为什么需要显示templatetypename的全面说明,请参阅:我必须在哪里以及为什么必须放置"模板"和"类型名"关键字?

typename不是

这样用的,所以这两种情况都是无效的,应该会产生编译错误,如下所示:

main.cpp:4:20: error: expected a qualified name after 'typename'
    const typename T* x;
                   ^

在这里,您需要类似T::myType的东西才能继续。

甚至这个,更糟糕的是:

main.cpp:4:14: error: expected a qualified name after 'typename'
    typename const T* x;
             ^
main.cpp:4:14: error: expected member name or ';' after declaration specifiers

相关示例在"typename"之后预期一个限定名称。


引入关键字 typename 是为了指定后面的标识符是类型

阅读更多: 正式地,typename有什么用?

在这里使用typename是没有意义的。

如果要访问别名类型(如 T::type(,则必须使用typenameT::type之间不能const

const typename T::type * x;  // ok
typename T::type const * x;  // ok
typename const T::type * x;  // error