将可变参数列表插入向量中?

新手上路,请多包涵

如果这已经回答了,请原谅我,因为我找不到它……

基本上我有一个对象需要在它的构造函数中获取一个可变参数列表并将参数存储在一个向量中。如何从可变参数构造函数的参数初始化向量?

 class GenericNode {
public:
    GenericNode(GenericNode*... inputs) {
            /* Something like... */
        // inputs_.push_back(inputs)...;
}
private:
    std::vector<GenericNode*> inputs_;
};

原文由 fredbaba 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 685
2 个回答

最好 的办法是使用初始化列表

#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

原文由 Mooing Duck 发布,翻译遵循 CC BY-SA 3.0 许可协议

除非它是模板,否则您不能使用可变参数列表,如前所述,您可以像这样使用 initializer_list:

 class GenericNode {
public:
    GenericNode(std::initializer_list<GenericNode*> inputs) : inputs_(inputs)
    {
    }
private:
    std::vector<GenericNode*> inputs_;
};

template <class ... T>
GenericNode* foo(T ... t)
{
    return new GenericNode({t...});
}

原文由 Luke B. 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题