c++ - Only overload operator if template argument does -
given template class single template argument t, possible overload operators in available type t? example:
template <typename t> class { public: #if hasoperator(t, +=) t& operator +=(const t &rhs) { mvalue += rhs; return mvalue; } #endif private: t mvalue; } int main() { a<int> a; += 8; //+= forward += int struct test { /*no operators defined*/ }; a<test> b; //+= not implemented since test not implement += } i'm writting generic wrapper class needs behave template type. if t has operator +=, (at compile time) overload += accordingly. yes, go ahead , implement every operator in a, compiler error when t doesn't have operator. @ first though template specialization might answer, require specialization every type. while work , lot of typing, wont because needs work type (not specialized).
use expression sfinae drop operator+ overload resolution set unless t defines operator+
template <typename t> class { private: t mvalue; public: template<typename u=t> auto operator +=(const u &rhs) -> decltype(mvalue += rhs) { mvalue += rhs; return mvalue; } };
Comments
Post a Comment