我有一个将大小作为模板参数的类(现场演示):
template <std::size_t SIZE> class A
{
char b[SIZE];
}
它有多个用于不同目的的构造函数:
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{} {}
使用这组构造函数,这个指令没有问题:
// 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);
但是在调用时A<5>("five")
,构造函数 2、3、4 和 5 之间存在模棱两可的调用。
所以我的问题是:
- 为什么构造函数 3 比构造函数 5 更受青睐
CASE 1
? A<SIZE>
当使用与模板参数大小相同的静态数组构造对象时,有没有办法消除构造函数 2、3、4、5 的歧义?
感谢您的关注。