Question

I have always thought that function template argument deduction can work only for pure function like below and not for classes.

template <class T1,class T2, class T3>
T foo(T2 a, T3 b)
{
   T o;
   //..do something
   return o;
}

Today Just by chance I put such function within a class and it did work like below.

class MyClass 
{
public:
   template <class T1,class T2, class T3>
   T foo(T2 a, T3 b)
   {
     T o;
     //..do something
     return o;
   }
}

I am using g++ 4.4 in Linux. Should this have failed or I misunderstood?

Was it helpful?

Solution 2

Template deduction works for function and for method.

If you have template class, something like:

template <class T1, class T2>
class MyClass 
{
public:
   MyClass(T1 a, T2 b)
};

You can't deduce type with something like

MyClass m(42, 53);           // Illegal
auto m = MyClass(42, 53);    // Illegal

You have to explicitly give type:

MyClass<int, int> m(42, 53); // Legal 

OTHER TIPS

I have always thought that function template argument deduction can work only for pure function like below and not for classes.

It's wrong. There is no difference in deduction in free-functions and in member-functions.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top