c++ - 在 C++ 中,typename 应该在 const 之前还是之后?

标签 c++ class oop constants typename

我应该写:

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(); 会出现编译错误

expected nested-name-specifier before 'const'

在哪里

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

工作得很好。


有关 templatetypename 需要出现的时间、地点和原因的全面解释,请参阅:Where and why do I have to put the "template" and "typename" keywords?

关于c++ - 在 C++ 中,typename 应该在 const 之前还是之后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43898730/

相关文章:

c++ - 真正基础的 SSE

parameters - 处理大量输入参数,大量输出

c++ - 不完整类型循环依赖c++的无效使用

c++ - 对象数组

java - 为什么 Java 不理解我放在这个多维数组中的对象的类?

ios - 是否可以使用变量动态更改代码中类的名称?

java - 使用类层次结构中的某些子类

c++ - 在我的代码中除以零

c++ - C++ 可移植开源应用程序的最佳实践

c++ - 内部成员在类里面的可见性