Antoine C.
Antoine C.

Reputation: 3952

Optional templated parameters for a function

I have a function in a class I want to use, whose definition is:

 template <typename T>
 class FooClass
 {
 /* [...] */
 public:
     template <typename TT>
     void myFunction(int a, FooClass& b, int c,
                     int d, TT optional_e = static_cast<TT>(1));
 }

I tried to call it this way:

obj.myFunction(a, b, c, d);

With all the arguments matching the types they should have.

However, Visual Studio throws an error at compile time:

C2783 : could not deduce template argument for TT

But if I try to call the function this way, it compiles without errors:

obj.myFunction(a, b, c, d, 0);

My question is, why can't I call the function without the optional parameter? How to do this?

Upvotes: 2

Views: 2404

Answers (2)

songyuanyao
songyuanyao

Reputation: 172904

Becuase template argument deduction can't be done by default argument; TT can't be deduced.

Type template parameter cannot be deduced from the type of a function default argument

You could specify the template argument explicitly:

obj.myFunction<int>(a, b, c, d);

Or give the template parameter TT a default type too. e.g.

template <typename TT = T>
void myFunction(int a, FooClass& b, int c,
                int d, TT optional_e = static_cast<TT>(1));

Note you still could specify the type explicitly for it.

Upvotes: 3

yeputons
yeputons

Reputation: 9238

All template arguments (e.g. TT) should be known in the place of the call in order to understand what TT is inside the function.

If you call the function the all the parameters, compiler see that type of the fourth argument is TT and, therefore, can deduce what TT is. E.g. if it's zero, then TT = int.

On the other hand, if you specify three parameters only, compiler have absolutely no idea about what TT should be. Therefore, it cannot choose which version of myFunction to call- is itmyFunction,myFunctionor evenmyFunction`?

If you want some "default" value for TT, you should specify that explicitly:

 template <typename TT = int>
 void myFunction(int a, FooClass& b, int c,
                 int d, TT optional_e = static_cast<TT>(1));

Upvotes: 3

Related Questions