Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why argument conversion is not considered when calling a templated function?

Tags:

c++

templates

I have a template class and a friend operator* function

StereoSmp<TE> operator* (const StereoSmp<TE>& a, TE b)

I use it with TE=float but I need to multiply a StereoSmp<float> * double I think that should be possibile because it should converts double to float automatically and works but I get the error:

no match for ‘operator*’ (operand types are ‘StereoSmp<float>’ and
    ‘__gnu_cxx::__alloc_traits<std::allocator<double> >::value_type {aka double}’) 
deduced conflicting types for parameter ‘TE’ (‘float’ and ‘double’)

Why it doesn't convert double to float automatically? And what can I do to allow the automatic conversion between types?

like image 324
Andrea993 Avatar asked May 02 '26 23:05

Andrea993


1 Answers

Don't make your friend a template.

template<class TE>
struct StereoSmp {
  friend StereoSmp operator* (const StereoSmp& a, TE b) {
    return multiply( a, b ); // implement here
  }
};

this is a non-template friend to each type instance of the template StereoSmp. It will consider conversions.

Template functions don't consider conversions, they simply do exact pattern matching. Overload resolution is already insane enough in C++.

like image 58
Yakk - Adam Nevraumont Avatar answered May 05 '26 13:05

Yakk - Adam Nevraumont



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!