基构造函数和派生构造函数之间的歧义
Ambiguity between base and derived constructors
我设计了以下代码片段来显示我的问题(原始代码片段更复杂):
#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 是一项解决当前规范众多问题的提案,在上次委员会会议上通过了设计审查,如果获得通过,将解决您的问题。
解决方法是在B
中编写一组委托构造函数,而不是使用默认参数:
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) {}
这将禁止从继承该基类构造函数中声明的所有三个签名。
如果定义派生类构造函数,则应在初始化列表中调用基类构造函数,如下所示:
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, int p2 = 0, int p3 = 0):A(p1,p2,p3) {}
};
请注意,您不需要使用 using 语句来解决派生类中的歧义,如 using A::A;
。当您公开派生时,您将获得基类的所有公共和受保护组件将在派生类中可用。
演示:http://coliru.stacked-crooked.com/a/52451127e54c8591
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 数组初始值设定项的构造函数歧义
- C++ 类的构造函数和函数调用运算符 () 重载之间的歧义
- C++ 显式多参数构造函数歧义
- c++ 构造函数重载歧义与initializer_list
- 解决C++构造函数和调用歧义
- 使用 std::initializer_list 构造函数而不产生歧义?
- 如何解决转换构造函数和普通构造函数之间的歧义
- 如何处理默认构造函数和重载构造函数之间的歧义
- C++11:在按值传递参数初始化时转换构造函数和转换函数之间的歧义
- 当目标类有多个构造函数时,消除强制转换操作符的歧义
- 构造函数在尝试支持文字时重载歧义
- 重载构造函数之间的歧义
- 为什么这两个构造函数一起不会产生歧义错误?
- 基构造函数和派生构造函数之间的歧义