I am trying to overload a multiplication operator but do not want to type out multiple overloaded functions to take into account multiplying int and float, int and double, float and int, etc... I was hoping to write one overloaded operator to account for all combinations of multiplication with floats, ints, and doubles and get the proper return type. I am getting errors saying that no operator found which takes a right-hand operand of type 'Widget::Widget' (or there is no acceptable conversion). I think this is because I am using the decltype to set the template type of the return object, the Widget. Using a trailing return type works if the return is not a template object.
Here is an example of the overloaded operator I am trying to make:
template<typename T1, typename T2>
auto
operator*(const Widget<T1>& aWidge, const Widget<T2>& bWidge) -> Widget<decltype(aWidge.x*bWidge.x)>
{
Widget<decltype(aWidge.x*bWidge.x)> result;
//do stuff needed when multiplying two Widgets
return result;
}
template<typename T>
Widget<T>& Widget<T>::operator=(const Widget<T>& aWidget)
{
x = aWidget.x;
return *this;
}
And here is an example of the template class
template<typename T> class Widget
{
private:
T x;
public:
Widget();
~Widget();
void SetX(T value);
Widget<T>& operator=(const Widget<T>& aWidget);
}
Example Main.cpp
int main()
{
Widget<int> aWidge;
Widget<float> bWidge;
Widget<float> cWidge;
aWidge.SetX(2);
bWidge.SetX(2.0);
cWidge = aWidge*bWidge; //this should give a float return type
}
operator =
forWidget<T>
to properly resolve the member operator, i.e.Widget<T>& Widget<T>::operator=(const Widget<T>& aWidget)
– WhozCraigoperator=
properly, usedeclval<T1>()
(etc.) instead ofaWidge.x
to get around private variable access, define/default the missing functions). Perhaps you can post a minimal compilable example that illustrates the problem, along with the compiler, version, and platform you're on. – Adam H. Peterson