0
#include <iostream>

namespace oo{

  class A{
  public:
    template<typename T>
    static T get_value(){return static_cast<T>(55);}
  };

  template <typename T=A>
  class B{
    public:
    static double f(){return T::get_value<double>();}
  };

}

int main(int argc, char *argv[])
{
  using std::cout;
  using std::endl;

  cout << oo::B<oo::A>::f() << endl;

  return 0;
}

Considering the example up here, it compiles with an error "type name is not allowed" which refers to "double" and arguments in "get_value()".

Someone has righted this wrong by rewriting the function f() as followed:

static double f(){return T::template get_value<double>(); }

Yet, I do not quite understand the use of "template" here. Could anyone explain that to me, please?

Thanks in advance for your comments.

Paul Bellora
  • 51,514
  • 17
  • 127
  • 176
Alex
  • 75
  • 4

2 Answers2

0

this is what's going on at runtime.

namespace oo{

  class A{  
  public:
   // template<typename T>  // T replaced with <double> type.
    static double get_value(){return static_cast<double>(55);}
  };

  //template <typename T=A> // T replaced with <oo::A> type.
  class B{
    public:
    static double f(){return oo::A::get_value/*<double>*/();}
  };

}

int main(int argc, char *argv[])
{
  using std::cout;
  using std::endl;

  cout << oo::B::f() << endl;

  return 0;
}

this line : static double f(){return T::get_value();} is correct and usually will be compiled without any errors(depend on witch compiler you're using), because the template declaration will be valid for the next scope.

template <class T>
class foo
{
   //T will be valid in this scope.
};

this is not the case to implement template classes/functions, you usually want to do that in cases where you want to prevent the using of multiple overloading.

Wagdi Kala
  • 63
  • 5
0

The reason is how the compiler interpret that line, when you use templates, the syntax has more than one possible interpretation, take a look to the following :

static double f()
{
    return T::get_value < double > ();
}

in your function, how you now that the T parameter passed to the B class has a function named get_value or a data member named get_value ? If the case is the second then you are using the operator lees-than between that member and double, and then between double and (). Well the first assumption of the compiler is these option, if you wat to tell him that this is a function with template (for the correct interpretation of "<") you need to put the keyword template

hidrargyro
  • 259
  • 1
  • 7