c++ - 转发 C++0x 中的所有构造函数

标签 c++ templates constructor c++11

在 C++0x 中转发所有父级构造函数的正确方法是什么?

我一直在这样做:

class X: public Super {
    template<typename... Args>
        X(Args&&... args): Super(args...) {}
};

最佳答案

C++0x 中有一个更好的方法

class X: public Super {
  using Super::Super;
};

如果您声明一个完美转发模板,您的类型将在重载解析中表现不佳。想象一下你的基类可以从 int 转换,并且有两个函数可以打印出类

class Base {
public:
  Base(int n);
};

class Specific: public Base {
public:
  template<typename... Args>
    Specific(Args&&... args);
};

void printOut(Specific const& b);
void printOut(std::string const& s);

你用

来调用它
printOut("hello");

会叫什么?这是模棱两可的,因为 Specific 可以转换任何参数,包括字符数组。它这样做不考虑现有的基类构造函数。使用 using 声明继承构造函数只声明完成这项工作所需的构造函数。

关于c++ - 转发 C++0x 中的所有构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3119929/

相关文章:

c++ - 声明为 void 的变量或字段

c++ - 为什么我不能将 LDBL_EPSILON 添加到 1

c++ - 如何使用 decltype 作为模板类返回类型的模板参数?

c++ - 在 C++ 中,从模板函数中调用模板函数获取指针的值

c++ - 牡丹 AES-256,32 位 InitialVector

c++ - 当您不取消引用时,指针不只是一个引用吗?

c++ - 使用类模板需要数组的模板参数列表

c++ - 与 get_instance() 分离的单例构造函数

c# - XMLSerializer - 无参数构造

c++ - 了解构造函数的一些具体情况