C++ base class constructor taking derived class as argument (?)

Your Vector class has two constructor: a template one (intended for values) and the default copy constructor.

Problem: the copy constructor is preferred but only if there is an exact match.

So, initializing b with a

mu::Vector<2, int> a{1, 2};
mu::Vector<2, int> b{a};

the copy constructor is preferred because a is an exact match

But, initializing h with g

mu::Vector2D<int> g{1, 2};
mu::Vector<2, int> h{g};

g can be converted to a mu::Vector<2, int> but isn’t an exact match, so the template constructor is preferred but the template constructor is incompatible.

A possible solution: SFINAE disable the template constructor when the there is only one argument and the argument is derived from mu::Vector.

For example

template <typename... TArgs,
          typename std::enable_if_t<sizeof...(TArgs) == N
                                or (not std::is_base_of_v<Vector, TArgs> && ...), int> = 0>
Vector(TArgs const & ... args) : data({args...}) {}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top