Reputation: 3455
I've created a class in C++, which has constructors for unsigned short
, signed short
, `const char*
, etc. I'd like to overload operators for all these classes. What is the most effective way to do it? Do I really need to write a function for each operator and each type or there can be used some magic?
I'd like to overload situations where variable of new type can be to the left or to the right from other types. Also, I'd like to adjust some types, e.g. new type Int must return new type Float if I add float, double or Float. Is this all possible without manually written functions for each type?
Thanks in advance!
Upvotes: 0
Views: 111
Reputation: 56479
For second part of your question, you can return an adjusted type:
template <typename T>
class Class
{
T data;
public:
Class (const T& data) : data(data) {}
template <typename U>
auto operator+(const U &x) -> typename std::common_type<T, const U&>::type
// ^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
{
return data + x;
}
};
int main()
{
Class<int> obj(10);
double x = obj + 12.5;
}
I hope I understood your question fine
Upvotes: 1