键入名称应该在 C++ 中常量之前还是之后
Should typename be before or after const in C++?
>我应该写:
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();
工作得很好。
有关何时、何地以及为什么需要显示template
和typename
的全面说明,请参阅:我必须在哪里以及为什么必须放置"模板"和"类型名"关键字?
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
(,则必须使用typename
和T::type
之间不能const
const typename T::type * x; // ok
typename T::type const * x; // ok
typename const T::type * x; // error
相关文章:
- #定义c-预处理器常量..我做错了什么
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 用C++中的一个变量定义一个常量
- 什么时候在C++中返回常量引用是个好主意
- 代理对象的常量正确性
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 通过多个头文件使用常量变量
- 在cuda线程之间共享大量常量数据
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 在类定义之后定义一个私有方法
- 是默认情况下分配给char数组常量的值
- 在循环C++中指定字符串之后,不会打印该字符串
- 私有类型的静态常量成员
- 键入名称应该在 C++ 中常量之前还是之后
- 类型之前或之后的常量
- 在声明C++之后初始化常量变量
- 为什么C++不允许在 ::之后使用常量?
- 在方法名称之前或之后放置常量、静态和虚拟
- 参数之前的常量与函数名称 C++ 之后的常量