apalomer
apalomer

Reputation: 1935

Template class copy construcor from different type: should it follow the Rule of Five?

I have the following class:

template <typename T>
class A
{
public:
  A(const T& value): m_value(value)
  {
  }

  template <typename M>
  A(const A<M>& other): A(T(other.m_value))
  {
  }

private:
  T m_value;
};

Should this class follow the Rule of Five? Or template <typename T>template <typename M> A<T>::A(const A<M>& other) is not considered a copy constructor?

Upvotes: 0

Views: 193

Answers (2)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385264

The rule of five exists because if you have a copy constructor then that's probably because you can't use the automatically-generated one, which in turn is probably because you have some indirection that needs to be taken care of. When that's so, you usually also need to take care of it during assignment and destruction.

What you have is not a copy constructor. It converts from another type. There is no indication in your code that the member m_value needs special handling during assignment or destruction. Furthermore, the copy-constructor that you do have performs no special operations.

If you can think of some code that you need to put in said special member functions, then go ahead and do it. Otherwise, you don't need them.

General rules can be useful but you do ultimately still need to make design decisions based on thinking! You don't implement functions just because a rule of thumb said that you may need to.

Upvotes: 3

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

According to the C++ Standard (15.8.1 Copy/move constructors)

1 A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments

So this

  template <typename M>
  A(const A<M>& other): A(T(other.m_value))
  {
  }

is not a copy constructor. It is a conversion constructor.

I do not see here the relation with the Rule of Five.

Upvotes: 1

Related Questions