Officially, what is typename for?

后端 未结 8 1672
野的像风
野的像风 2020-11-22 15:07

On occasion I\'ve seen some really indecipherable error messages spit out by gcc when using templates... Specifically, I\'ve had problems where seemingly correc

8条回答
  •  半阙折子戏
    2020-11-22 15:37

    I think all of the answers have mentioned that the typename keyword, is used in two different cases:

    a) When declaring a template type parameter. e.g.

    template class MyClass{};        // these two cases are
    template class MyNewClass{};  // exactly the same.
    

    Which there is no difference between them and they are EXACTLY the same.

    b) Before using a nested dependent type name for a template.

    template
    void foo(const T & param)
    {
       typename T::NestedType * value; // we should use typename here
    }
    

    Which not using typename leads to parsing/compilation errors.

    What I want to add to the second case, as mentioned in Scot Meyers book Effective C++, is that there is an exception of using typename before a nested dependant type name. The exception is that if you use the nested dependant type name either as a base class or in a member initialization list, you should not use typename there:

    template
    class D : public B::NestedType               // No need for typename here
    {
    public:
       D(std::string str) : B::NestedType(str)   // No need for typename here
       {
          typename B::AnotherNestedType * x;     // typename is needed here
       }
    }
    

    Note: Using typename for the second case (i.e. before nested dependent type name) is not needed since C++20.

提交回复
热议问题