Re: Generic operator implementation, pointer to POD type's operators
johan.torp@gmail.com ha scritto:
Is it possible to get a pointer to the built in types' operators? Some
construct like &int::operator+= that is.
It's not possible.
I'm trying to forward some operators (+=, -=, *= and so on) to a
generic function, is there some other solution to this problem? See
the pseudo code below.
Why are you using pointer to function in the first place where you could
use functors instead? You don't even have to invent functions because
the STL already define most of them for you:
template<class T>
struct X
{
X& operator+=(const T& t)
{ return operator_impl(t, std::plus<T>()); }
X& operator-=(const T& t)
{ return operator_impl(t, std::minus<T>()); }
X& operator*=(const T& t)
{ return operator_impl(t, std::multiplies<T>()); }
X& operator/=(const T& t)
{ return operator_impl(t, std::divides<T>()); }
X& operator%=(const T& t)
{ return operator_impl(t, std::modulus<T>()); }
/* etc. you will have to provide functors for & | and ^
because the STL unfortunately doesn't have them */
private:
T t2;
template <class Func>
X& operator_impl(const T& t, Func f)
{
...
f(t2, t); // call the correct operator
...
return *this;
}
};
As an added benefit, with the functor approach the operation will
probably be expanded inline, avoiding a function call.
HTH,
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]