我尝试使用一些数据成员扩展基类,因此除了我的基类需要的构造函数参数之外还需要一些额外的构造函数参数。我想将第一个构造函数参数转发给基类。这就是我的尝试:
#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试图告诉我,我的模板化构造函数只有一个参数,即使参数的数量是可变的?我该如何解决这个问题?
答案 0 :(得分:3)
你必须将varargs移动到参数列表的末尾。
#include <string>
#include <utility>
struct X
{
X( int i_ ) : i(i_) {}
int i;
};
struct Y : X
{
template <typename ...Ts>
Y( std::string s_, Ts&&...args ) // <==== like this
: X( std::forward<Ts>(args)... )
, s( std::move(s_) )
{}
std::string s;
};
int main()
{
Y y( "", 1 );
}
答案 1 :(得分: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;
}