我设计了下面的代码片段来展示我的问题(原来的更复杂):
#include <string>
struct A
{
A(int, int) {}
A(int p1 = 0, std::string p2 = "", int p3 = 0) {} // string for breaking ambiguity with previous ctor
// There are a lot more of constructors for A class
};
struct B : public A
{
using A::A; // I want to inherit many base constructors in order to save work
// But I need this particular constructor and it should override the
// equivalent base constructor
B(int p1 = 0, std::string p2 = "", int p3 = 0) {}
};
int main(int argc, char *argv[])
{
B b(1); // gives "error: call to constructor of 'B' is ambiguous", what
// of course is true, but I would want to inherit the other
// base constructors. If I comment using A::A ==> this line compiles
B b2(2, 3); // But if I comment using A::A ==> this line does not compile
}
那么,我的问题是:有没有什么方法可以打破这种歧义而不隐藏许多其他具有基类的构造函数?
提前致谢
最佳答案
当前的继承构造函数规范是......有点困惑。继承 A(int p1 = 0, std::string p2 = "", int p3 = 0)
构造函数隐式声明三个签名:B(int)
, B(int, std::string)
, B(int, std::string, int)
,只有最后一个因为B
而被抑制> 的构造函数声明。
N4429 ,一项解决当前规范中许多问题的提案,在上一次委员会 session 上通过了设计审查,如果被采纳,将解决您的问题。
解决方法是在 B
中编写一组委托(delegate)构造函数,而不是使用默认参数:
B() : B(0) {}
B(int p1) : B(p1, "") {}
B(int p1, std::string p2) : B(p1, std::move(p2), 0) {}
B(int p1, std::string p2, int p3) {}
这会抑制所有三个声明继承该基类构造函数的签名。
关于c++ - 基础构造函数和派生构造函数之间的歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30794078/