2017-05-10 117 views
2

我应该写:应该在C++的const之前或之后使用typename?

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

或:

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

是'typename'甚至不允许在这种情况下?我认为它仅用于消除静态数据成员和成员类型的语法。 –

+3

如果其中任何一个导致编译错误,那就是你不应该使用的错误。 – molbdnilo

+0

简单地说:'template class Foo const T * x = nullptr; };' – Jarod42

回答

3

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 

expected a qualified name after 'typename'相关的例子。


关键字类型名称被介绍给指定后面的标识符是一种

详情请阅读:Officially, what is typename for?

1

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 typename T::iterator bar = t.begin(); 

工作得很好。


有关何时,何地,为什么templatetypename需要看到出现一个全面的解释:Where and why do I have to put the "template" and "typename" keywords?

0

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

你将不得不使用,如果你要访问的别名类型像T::type,你不能拥有和T::typeconst之间typename

const typename T::type * x; // ok 
typename T::type const * x; // ok 
typename const T::type * x; // error 
相关问题