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?
Generally no, but in gcc You may make the last parameter of funcA() optional with a macro.
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.
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.
Overloaded operators cannot have default arguments.
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){
...
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With