Search code examples
c++templatesfunction-template

getting result from a specific base in a templated class with variable number of templated arguments


I am trying to implement a templated class like below.

   struct Ciccio2 : public T1, public T2, public T3, public T4
   {
     template<typename TR>
     int get(const string& s) const
     {
       return TR::operator()(s);
     }
   };

All templated argument are like the following sample class

   struct AA{ 
     int operator()(const string& s) { return 1;}
   };

I am trying also to have a global extractor function but when I use the template function below g++ gives me a build error saying

   template<class TA, class T1, class T2, class T3, class T4>
   int extract(const Ciccio2<T1,T2,T3,T4>& obj, const string& s)
   {
     return obj.get<TA>(s);
   }

the code below doesn't buld saying

expected primary expression before > token

Is it correct what I am trying to implement?


Solution

  • Since obj is a type-dependent expression, the compiler won't use name lookup to determine whether obj.get is an object, function, type, or template. Unless you force it to do otherwise, the compiler assumes it is an object or function for syntax analysis. Next it sees the < less than operator (not the < beginning a template argument list), and soon afterward gets confused. You need:

    return obj.template get<TA>(s);
    

    See also the question Where and why do I have to put the template and typename keywords?