Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C++ deduce argument type from default value?

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?

like image 400
Dave11ar Avatar asked Nov 29 '21 14:11

Dave11ar


People also ask

Can C have default arguments?

Generally no, but in gcc You may make the last parameter of funcA() optional with a macro.

Can a function argument have default value?

Once a default value is used for an argument in the function definition, all subsequent arguments to it must have a default value as well. It can also be stated that the default arguments are assigned from right to left.

How can we pass arguments to functions by default?

By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.

Which operator Cannot default arguments?

Overloaded operators cannot have default arguments.


2 Answers

The type of a template parameter in a function can't be deduced from a default argument. As shown in the example on cppreference.com:

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)
}

However, you can specify a default argument for the template parameter:

template<typename A, typename B = int>
void func(int i1, int i2, A a, B b = 123){
    ...
}
like image 191
songyuanyao Avatar answered Oct 10 '22 23:10

songyuanyao


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);
}
like image 12
463035818_is_not_a_number Avatar answered Oct 10 '22 23:10

463035818_is_not_a_number