是否可以编写可变参数模板构造函数来初始化 class/struct 的所有成员?
Is it possible to write variadic template constructor initializing all members of a class/struct?
是否可以实现:
struct S
{
int a;
std::string s;
template<typename... Args>
S(Args... args)
: // what next?
{
// what next?
}
};
或者有没有其他方法可以实现(类似)这个? (std::tuple?)
您可以使用 std::tie
为您的数据成员创建 左值引用 的元组,并分配基于传递的参数创建的另一个元组的内容:
struct S {
int a;
std::string s;
template<typename... Args>
S(Args&&... args) {
static_assert(std::is_same_v< std::tuple<int,std::string>, std::tuple<std::decay_t<Args>...> >);
std::tie(a,s) = std::forward_as_tuple(std::forward<Args>(args)...);
}
};
int main(){
std::string str("x");
S s(10,str); // ok
S s4(1,std::string("x")); // ok
//S s2(10,"x"); // fails
//S s3(10,0); // fails
是否可以实现:
struct S
{
int a;
std::string s;
template<typename... Args>
S(Args... args)
: // what next?
{
// what next?
}
};
或者有没有其他方法可以实现(类似)这个? (std::tuple?)
您可以使用 std::tie
为您的数据成员创建 左值引用 的元组,并分配基于传递的参数创建的另一个元组的内容:
struct S {
int a;
std::string s;
template<typename... Args>
S(Args&&... args) {
static_assert(std::is_same_v< std::tuple<int,std::string>, std::tuple<std::decay_t<Args>...> >);
std::tie(a,s) = std::forward_as_tuple(std::forward<Args>(args)...);
}
};
int main(){
std::string str("x");
S s(10,str); // ok
S s4(1,std::string("x")); // ok
//S s2(10,"x"); // fails
//S s3(10,0); // fails