T
T
Timur Sharipov2015-12-01 21:00:41
C++ / C#
Timur Sharipov, 2015-12-01 21:00:41

How to provide an implicit call of the template class constructor in the overridden operator?

First, let's create a class that stores a numeric value:

class MyVal {
public:
  int val_;

  MyVal(int val = 0) : val_(val) {}
};

Let's redefine the + operator:
MyVal operator *(const MyVal &x, const MyVal &y) 
{
  return MyVal(x.val_ * y.val_);
}

Next, we multiply MyVal directly by the number (this creates an instance of MyVal for the value 1):
MyVal a, b;
  b = 1 * a;

If the class becomes a template
template<class T>
class MyVal {
public:
  T val_;

  MyVal(T val = 0) : val_(val) {}
};

template<class T>
MyVal<T> operator *(const MyVal<T> &x, const MyVal<T> &y) 
{
  return MyVal<T>(x.val_ * y.val_);
}

void Test()
{
  MyVal<int> a, b;
  b = 1 * a;
}

then the compiler throws " error C2677: binary '*' : no global operator found which takes type 'MyVal' ". The problem is that adding operator *(const MyVal &x, T val) is possible, but undesirable. Looking for a way to achieve implicit creation of MyVal...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Timur Sharipov, 2015-12-02
@shtr

It looks like the best option is a specialization:

MyVal<int> operator *(const MyVal<int> &x, const MyVal<int> &y) 
{
  return MyVal<int>(x.val_ * y.val_);
}

I
iv_k, 2015-12-02
@iv_k

b = MyVal<int>(1) * a;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question