从 C++11 开始,可以有两个复制构造函数,一个接受 type 参数,T&
一个接受 type 参数const T&
。
我有一种情况,当构造函数在派生类中继承时,(似乎)添加第二个复制构造函数会导致没有一个被调用。当两者都存在时,复制构造函数会被模板化构造函数覆盖。
这是一个MWE:
struct A {
template <typename... Args>
A (Args&&... args)
{ std::cout << "non-default ctor called\n"; }
A (A&) { std::cout << "copy ctor from non-const ref\n"; }
};
struct C :public A { using A::A; };
int main() {
C c1;
C c2(c1);
}
运行这段代码,我们看到输出
non-default ctor called
copy ctor from non-const ref
这是预期的。
但是,添加一个额外的构造函数struct A
如下:
A (const A&) { }
不知何故导致另一个复制构造函数不被调用,所以输出变成
non-default ctor called
non-default ctor called
在我的用例中,我想将所有构造函数从基类继承到派生类中,包括复制构造函数和其他任何东西。但似乎这两个复制构造函数在它们都存在时不会被继承。这里发生了什么?