Ok, let's say I have a function like this
template <typename T>
void Func(std::vector<T> x, T alpha = 1)
{
// ... do stuff
}
and I would like to use it with a complex type, like this
std::vector<std::complex<double>> x;
Func(x, 5.5);
Then the compiler complains (VS2010) that template parameter 'T' is ambiguous because it could be 'double' or 'std::complex<double>'. Obvious fix, call it like this
Func(x, std::complex<double>(5.5));
but, that, I don't want. Why can't it be converted to a complex type automatically?
The reason it doesn't work is because the first argument causes T to be deduced as std::complex<double> whereas the second argument causes it to be deduced as double. It simply doesn't consider conversions when deducing arguments. Obviously, this makes the deduction ambiguous.
You can force the second argument type to be non-deducable with the help of an identity helper:
template <typename T>
struct identity { typedef T type; };
template <typename T>
void Func(std::vector<T> x, typename identity<T>::type alpha = 1)
{
// ... do stuff
}
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