Re: Generic operator implementation, pointer to POD type's operators
On May 26, 12:54 pm, johan.t...@gmail.com wrote:
Is it possible to get a pointer to the built in types' operators? Some
construct like &int::operator+= that is.
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.
template<class T>
struct X
{
X& operator+=(const T& t) { return operator_impl(t2, t,
&T::operator+= ); }
X& operator-=(const T& t){ return operator_impl(t2, t,
...
private:
T t2;
typedef T&(*operatorFunc)(T&, const T&);
X& operator_impl(const T& t, operatorFunc f)
{
...
// call the correct operator
(*f)(t2, t);
...
return *this;
}
};
The code you have here wouldn't work anyway. I don't know
if this is a C++ language requirement (any experts care to
comment?), but the =op operators are usually member functions,
which can't be called this way.
A better way, which also gets around the built-in type problem,
is to create a helper function for each =op operator. Since
it uses the operator as an operator, it doesn't care how the
operator is defined (or if it's a built-in operator.)
Here's some untested code that illustrates the idea:
template <class T> struct X
{
...
private:
void my_equals_plus( T t ) { t2 += t; }
...
public:
X & operator+=( T t ) { operator_impl( t,
&X::my_equals_plus ); return *this; }
private:
void operator_impl( T t, X & (X::*f)( T t ) )
{
...
this->*f( t );
...
}
....
};
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]