c++ - 如何派生新参数并将其添加到构造函数的基本版本?

标签 c++ c++11 inheritance constructor variadic-templates

我试图用一些数据成员扩展一个基类,因此除了我的基类需要的构造函数参数之外,还需要一些额外的构造函数参数。我想将第一个构造函数参数转发给基类。这是我尝试过的:

#include <string>
#include <utility>

struct X
{
    X( int i_ ) : i(i_) {}
    int i;
};

struct Y : X
{
    template <typename ...Ts>        // note: candidate constructor not viable: 
    Y( Ts&&...args, std::string s_ ) // requires single argument 's_', but 2 arguments 
//  ^                                // were provided
    : X( std::forward<Ts>(args)... )
    , s( std::move(s_) )
    {}

    std::string s;
};

int main()
{
    Y y( 1, "" ); // error: no matching constructor for initialization of 'Y'
//    ^  ~~~~~
}

然而,编译器(clang 3.8,C++14模式)向我吐出以下错误信息(为了阅读方便,主要信息也在上面的源代码中):

main.cpp:23:7: error: no matching constructor for initialization of 'Y'
    Y y( 1, "" );
      ^  ~~~~~
main.cpp:13:5: note: candidate constructor not viable: requires single argument 's_', but 2 arguments were provided
    Y( Ts&&...args, std::string s_ )
    ^
main.cpp:10:8: note: candidate constructor (the implicit move constructor) not viable: requires 1 argument, but 2 were provided
struct Y : X
       ^
main.cpp:10:8: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 2 were provided
1 error generated.

为什么 clang 试图告诉我,我的模板化构造函数只有一个参数,即使参数的数量是可变的?我该如何解决这个问题?

最佳答案

这是一个可能的解决方案:

#include <string>
#include <utility>
#include<functional>
#include<tuple>
#include<iostream>

struct X
{
    X( int i_ ) : i(i_) {}
    int i;
};

struct Y : X
{
    template<std::size_t... I, typename... A>
    Y(std::integer_sequence<std::size_t, I...>, std::tuple<A...> &&a)
        : X( std::get<I>(a)... ),
          s(std::move(std::get<sizeof...(I)>(a)))
    { }

    template <typename ...Ts>
    Y( Ts&&...args )
        : Y{std::make_index_sequence<sizeof...(Ts)-1>(),
          std::forward_as_tuple(std::forward<Ts>(args)...)}
    { }

    std::string s;
};

int main()
{
    Y y( 1, "foo" );
    std::cout << y.s << std::endl;
}

关于c++ - 如何派生新参数并将其添加到构造函数的基本版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37974603/

相关文章:

c++ - Cmake 和 Qt5 链接错误

C++ 编译器无法识别 std::stringstream::swap

c++ - C++03 和 C++11 类的区别

C++通过继承在具有 protected 构造函数的基类堆上分配对象

c++ - 具有继承类和函数的抽象类写入单独的 vector c++

c++ - 多继承C++的菱形继承(钻石问题)

c++ - 测试如何验证特定功能是否已执行

c++ - 交叉编译 "toolset"

C++11:在 std::array<char, N> 上定义函数

swift - 一种从多个类继承的方法