C++ template gotchas

后端 未结 4 791
梦谈多话
梦谈多话 2020-12-07 18:08

just now I had to dig through the website to find out why template class template member function was giving syntax errors:

template class F00         


        
4条回答
  •  半阙折子戏
    2020-12-07 18:49

    The star of questions about templates here on SO: the missing typename!

    template 
    class vector
    {
      public:
        typedef T * iterator;
        ...
    };
    
    template 
    void func()
    {
        vector::iterator it;           // this is not correct!
    
        typename vector::iterator it2; // this is correct.
    }
    

    The problem here is that vector::iterator is a dependent name: it depends on a template parameter. As a consequence, the compiler does not know that iterator designates a type; we need to tell him with the typename keyword.

    The same goes for template inner classes or template member/static functions: they must be disambiguated using the template keyword, as noted in the OP.

    template 
    void func()
    {
        T::staticTemplateFunc();          // ambiguous
    
        T::template staticTemplateFunc(); // ok
    
        T t;
    
        t.memberTemplateFunc();          // ambiguous
    
        t.template memberTemplateFunc(); // ok
    }
    

提交回复
热议问题