Reputation: 377
I'm looking for an elegant way (defined by minimal repeated code) to overload an operator to do the following:
I have a template class BaseSignal
which overloads the +=
operator, and I would like to be able to accept many different types. For example, for a double, the code looks like
template <class T>
class BaseSignal
{
public:
....
// Self-increment
BaseSignal<T>& operator+=(const double& rhs)
{
T rval;
this->Get(&rval);
this->Set(rval + static_cast<T>(rhs));
return *this;
}
....
What I've been doing is repeating this body of code for int, long, etc. Since the value rhs
is only used in the line static_cast<T>(rhs)
, I am repeating code while only changing the input parameter type.
So I could template this, e.g.
template <class T, class U>
class BaseSignal
{
public:
....
// Self-increment
BaseSignal<T>& operator+=(const U& rhs)
{
T rval;
this->Get(&rval);
this->Set(rval + static_cast<T>(rhs));
return *this;
}
....
But then it looks like I lose the "overloading" aspect in that the compiler would automatically select the correct method for me (it would also only work for the original U
type that was instantiated).
I realize that I am trying to achieve some untyped language behavior with C++, which may not be the smartest thing, I am just trying to add some intelligence to a few commonly-used classes so that subsequent code will become much easier to write.
Thank you in advance.
Upvotes: 2
Views: 59
Reputation: 218268
You might do
template <class T>
class BaseSignal
{
public:
// Self-increment
template <class U>
BaseSignal<T>& operator+=(const U& rhs)
{
T rval;
this->Get(&rval);
this->Set(rval + static_cast<T>(rhs));
return *this;
}
};
Upvotes: 5