Officially, what is typename for?

2019-01-01 04:44发布

On occasion I've seen some really indecipherable error messages spit out by gcc when using templates... Specifically, I've had problems where seemingly correct declarations were causing very strange compile errors that magically went away by prefixing the "typename" keyword to the beginning of the declaration... (For example, just last week, I was declaring two iterators as members of another templated class and I had to do this)...

What's the story on typename?

标签: c++ templates
7条回答
临风纵饮
2楼-- · 2019-01-01 05:40

Consider the code

template<class T> somefunction( T * arg )
{
    T::sometype x; // broken
    .
    .

Unfortunately, the compiler is not required to be psychic, and doesn't know whether T::sometype will end up referring to a type name or a static member of T. So, one uses typename to tell it:

template<class T> somefunction( T * arg )
{
    typename T::sometype x; // works!
    .
    .
查看更多
登录 后发表回答