I have a set of template classes inherited from a single base class:
template<typename Traits> class Base{ typedef typename Traits::scalar_t scalar_t; public: virtual ~Base(){} virtual scalar_t apply(const scalar_t&) const=0; }; template<typename Traits> class Pover_of_Number: public Base<Traits>{ typedef typename Traits::scalar_t scalar_t; public: Pover_of_Number(const scalar_t& power): power(power){} scalar_t apply(const scalar_t& value) const override{ return pow(value,power); } private: scalar_t power; }; template<typename Traits> class Mult_by_Number: public Base<Traits>{ typedef typename Traits::scalar_t scalar_t; public: Mult_by_Number(const scalar_t& num): num(num){} scalar_t apply(const scalar_t& value) const override{ return num*value; } private: scalar_t num; }; template<typename Traits> class SumOperator: public Base<Traits>{ typedef Base<Traits> BT; typedef typename Traits::scalar_t scalar_t; public: SumOperator(const std::shared_ptr<Base<Traits>>& op1, const std::shared_ptr<Base<Traits>>& op2): op1{op1}, op2{op2}{} scalar_t apply(const scalar_t& value) const override{ return op1->apply(value)+op2->apply(value); } private: std::shared_ptr<BT> op1; std::shared_ptr<BT> op2; }; The following code for a specific set of properties works without problems:
class TraitsExample{ public: typedef double scalar_t; }; int main(){ typedef typename TraitsExample::scalar_t scalar_t; auto op1=std::make_shared<Pover_of_Number<TraitsExample>>(2.); auto op2=std::make_shared<Mult_by_Number<TraitsExample>>(10.); auto sumop=std::make_shared<SumOperator<TraitsExample>>(op1,op2); scalar_t value=2.; std::cout<<sumop->apply(value)<<std::endl; } Having such a set of classes I need to overload the + operator. For example:
template<typename Traits> std::shared_ptr<SumOperator<Traits>> operator+( const std::shared_ptr<Base<Traits>>& op1, const std::shared_ptr<Base<Traits>>& op2){ return std::make_shared<SumOperator<Traits>>(op1,op2); } However, when compiling such a code, a problem occurs with automatic pattern recognition and an error occurs: template argument deduction/substitution failed .
Can someone suggest a code that allows the addition operator to be properly overloaded in this case?
PS: for convenience, you can find the code link