Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Small annoyance with template function

Tags:

c++

templates

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?

like image 225
demorge Avatar asked Dec 30 '25 13:12

demorge


1 Answers

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
}
like image 181
Joseph Mansfield Avatar answered Jan 02 '26 03:01

Joseph Mansfield