c++ - Can you use decltype in a template parameter? -
i trying overload multiplication operator not want type out multiple overloaded functions take account multiplying int , float, int , double, float , int, etc... hoping write 1 overloaded operator account combinations of multiplication floats, ints, , doubles , proper return type. getting errors saying no operator found takes right-hand operand of type 'widget::widget' (or there no acceptable conversion). think because using decltype set template type of return object, widget. using trailing return type works if return not template object.
here example of overloaded operator trying 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 2 widgets return result; } template<typename t> widget<t>& widget<t>::operator=(const widget<t>& awidget) { x = awidget.x; return *this; } and here example of 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 float return type }
visual studio 2012
don't mind sloppy code. quick fix code didn't compile begin (nevermind auto decltype problem).
template<typename t> class widget { public: t x; public: widget() : x(666) {} ~widget() {} void setx(t value) { x = value; } widget<t>& operator=(const widget<t>& awidget) { x = awidget.x; return *this; } }; template<typename t1, typename t2> auto operator*(const widget<t1>& awidge, const widget<t2>& bwidge) -> widget<typename std::remove_const<decltype(awidge.x*bwidge.x)>::type> { widget<typename std::remove_const<decltype(awidge.x*bwidge.x)>::type> result; result.x = awidge.x * bwidge.x; return result; } int main () { widget<int> awidge; widget<float> bwidge; widget<float> cwidge; awidge.setx(2); bwidge.setx(2.0); cwidge = awidge*bwidge; //this should give float return type }
Comments
Post a Comment