Home > database >  Can C deduce argument type from default value?
Can C deduce argument type from default value?

Time:11-30

I tried to write this function with a default template argument:

template<typename A, typename B>
void func(int i1, int i2, A a, B b = 123){
    ...
}

In my mind I can call it like this: func(1, 2, 3) and compiler should deduce type B as int from default value, but I get no instance of overloaded function.
Is it incorrect C construction and compiler can't deduce type in this case?

CodePudding user response:

Yes. Template parameter can't be deduced from function default argument.

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

template<typename T> void f(T = 5, T = 7); 

void g()
{
    f(1);     // OK: calls f<int>(1, 7)
    f();      // error: cannot deduce T
    f<int>(); // OK: calls f<int>(5, 7)
}

You can specify default argument for the template parameter too.

template<typename A, typename B = int>
void func(int i1, int i2, A a, B b = 123){
    ...
}

CodePudding user response:

As often when default arguments don't work you can use overloads:

template<typename A, typename B>
void func(int i1, int i2, A a, B b){
    ...
}
template<typename A>
void func(int i1, int i2, A a){
    func(i1,i2,a,123);
}
  • Related