fre*_*aba 26 c++ variadic-functions c++11
请原谅我已经回答了,因为我找不到它......
基本上我有一个对象需要在它的构造函数中获取可变参数列表并将参数存储在向量中.如何从可变参数构造函数的参数初始化向量?
class GenericNode {
public:
GenericNode(GenericNode*... inputs) {
/* Something like... */
// inputs_.push_back(inputs)...;
}
private:
std::vector<GenericNode*> inputs_;
};
Run Code Online (Sandbox Code Playgroud)
Moo*_*uck 26
的最好的事情是将使用初始化列表
#include <initializer_list>
#include <vector>
class GenericNode {
public:
GenericNode(std::initializer_list<GenericNode*> inputs)
:inputs_(inputs) {} //well that's easy
private:
std::vector<GenericNode*> inputs_;
};
int main() {
GenericNode* ptr;
GenericNode node{ptr, ptr, ptr, ptr};
} //compilation at http://stacked-crooked.com/view?id=88ebac6a4490915fc4bc608765ba2b6c
Run Code Online (Sandbox Code Playgroud)
使用C++ 11最接近你已经拥有的是使用vector的initializer_list:
template<class ...Ts>
GenericNode(Ts... inputs)
:inputs_{inputs...} {} //well that's easy too
//compilation at http://stacked-crooked.com/view?id=2f7514b33401c51d33677bbff358f8ae
Run Code Online (Sandbox Code Playgroud)
这是一个C++ 11版本,根本没有初始化列表.它很丑陋,很复杂,需要许多编译器缺少功能.使用初始化列表
template<class T>
using Alias = T;
class GenericNode {
public:
template<class ...Ts>
GenericNode(Ts... inputs) { //SFINAE might be appropriate
using ptr = GenericNode*;
Alias<char[]>{( //first part of magic unpacker
inputs_.push_back(ptr(inputs))
,'0')...,'0'}; //second part of magic unpacker
}
private:
std::vector<GenericNode*> inputs_;
};
int main() {
GenericNode* ptr;
GenericNode node(ptr, ptr, ptr, ptr);
} //compilation at http://stacked-crooked.com/view?id=57c533692166fb222adf5f837891e1f9
//thanks to R. Martinho Fernandes for helping me get it to compile
Run Code Online (Sandbox Code Playgroud)
与一切无关,我不知道那些是否拥有指针.如果是,请std::unique_ptr
改用.
// inputs_.push_back(inputs)...;
Run Code Online (Sandbox Code Playgroud)
这不起作用,因为您不能将参数包扩展为语句,仅在某些上下文中,例如函数参数列表或初始化列表.
您的构造函数签名也是错误的,如果您正在尝试编写可变参数模板,则需要将其作为模板!
正确编写构造函数签名后,答案很简单,只需使用包扩展构造向量:
#include <vector>
class GenericNode
{
public:
template<typename... T>
GenericNode(T*... inputs) : inputs_{ inputs... }
{ }
private:
std::vector<GenericNode*> inputs_;
};
Run Code Online (Sandbox Code Playgroud)
(您可以使用以下命令在构造函数体中设置它:
inputs_ = { inputs... };
Run Code Online (Sandbox Code Playgroud)
但酷孩子使用成员初始化器而不是在构造函数体中赋值.)
此解决方案的缺点是模板构造函数接受任何类型的指针参数,但如果参数不可转换为,则在尝试构造向量时会出错GenericNode*
.您可以将模板限制为仅接受GenericNode
指针,但如果您执行其他答案建议的操作并使构造函数采用std::initializer_list<GenericNode*>
,则会自动执行此操作,然后您不需要任何丑陋的enable_if
SFINAE技巧.
归档时间: |
|
查看次数: |
12592 次 |
最近记录: |