Search code examples
c++templatesoptional-parameterstemplate-argument-deduction

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?


Solution

  • 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.