的最好的事情是将使用初始化列表
#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
的最接近于你已经拥有,使用C++ 11是使用向量的initializer_list:
template<class ...Ts>
GenericNode(Ts... inputs)
:inputs_{inputs...} {} //well that's easy too
//compilation at http://stacked-crooked.com/view?id=2f7514b33401c51d33677bbff358f8ae
这里是一个没有initializer_lists的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
无关的一切,我不知道那些是拥有指针或没有。如果是,请改为使用std::unique_ptr
。
你的例子中有一些无效的语法。你想问什么? –
使用'std :: initializer_list'。 –
对不起。为了澄清,我该如何使用参数列表填充std :: vector? @MooingDuck,我会看看std :: initializer_list。谢谢。 – fredbaba