I have a class which takes a size as a template parameter (live demo):
template <std::size_t SIZE> class A
{
char b[SIZE];
}
It have multiple constructors for different purposes:
using const_buffer_t = const char (&)[SIZE];
using my_type = A<SIZE>;
A() : b{} {} // (1) no params
A(const_buffer_t) : b{} {} // (2) copy contents of given buffer
A(const char * const) : b{} {} // (3) copy as many items as they fit into the size
explicit A(const my_type &) : b{} {} // (4) copy constructor
// (5) copy as many items as they fit into the size
template <std::size_t OTHER_SIZE>
A(const char (&)[OTHER_SIZE]) : b{} {}
// (6) copy constructor from another sized A
// copy as many items as they fit into the size
template <std::size_t OTHER_SIZE>
explicit A(const A<OTHER_SIZE> &) : b{} {}
With this set of constructors there's no problem with this instructions:
// CASE 1
// Calls constructor 3: A<5>(const char * const)
// Expecting constructor 5: A<5>(const char (&)[11])
A<5> a("0123456789");
// CASE 2
// As expected, calls constructor 1: A<5>()
A<5> b();
// CASE 3
// As expected, calls constructor 4: A<5>(const A<5> &)
A<5> c(b);
// CASE 4
// As expected, calls constructor 6: A<5>(const A<9> &)
A<9> c(b);
But when calling A<5>("five")
there's an ambiguous call between the constructors 2, 3, 4 and 5.
So my questions are:
- Why the constructor 3 is preferred over the constructor 5 in the
CASE 1
? - Is there a way to disambiguate the constructors 2, 3, 4, 5 when the object
A<SIZE>
is constructed with a static array of the same size of the template parameter?
Thanks for your attention.