c++ - 基础构造函数和派生构造函数之间的歧义

标签 c++ c++11

我设计了下面的代码片段来展示我的问题(原来的更复杂):

#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/

相关文章:

.net - 通过 c++/cli 层从 c++ dll 使用 .net dll 时出现问题

c++ - 我如何在 KDevelop 中设置编译器选项?

c++ - 编译随机失败: "cannot open program database"

C++ 类型索引散列导致未定义的行为

C++11 和多态 lambda 的缺失——为什么?

c++ - 如何运行所有子目录 CMakeList 文件并捕获输出?

c++ - 使用 boost::asio::basic_stream_socket::async_read_some 而不是 boost::asio::async_read 是否更有效?

c++ - 为什么未初始化的 constexpr 变量不是常量?

C++11: `auto` 对 const 和引用类型的操作的标准引用

c++ - GMOCK如何为函数参数赋值