如何派生和添加新参数到构造函数的基本版本?

Ral*_*zky 5 c++ inheritance constructor variadic-templates c++11

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

#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'
//    ^  ~~~~~
}
Run Code Online (Sandbox Code Playgroud)

但是,编译器(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.
Run Code Online (Sandbox Code Playgroud)

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

sky*_*ack 3

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

#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;
}
Run Code Online (Sandbox Code Playgroud)