Inserting a variadic argument list into a vector?

后端 未结 6 1086
别那么骄傲
别那么骄傲 2020-12-09 02:44

Forgive me if this has been answered already, as I couldn\'t find it...

Basically I have an object that needs to take a variadic argument list in it\'s constructor

6条回答
  •  情话喂你
    2020-12-09 03:15

        // inputs_.push_back(inputs)...;
    

    This doesn't work because you can't expand a parameter pack as a statement, only in certain contexts such as a function argument list or initializer-list.

    Also your constructor signature is wrong, if you're trying to write a variadic template it needs to be a template!

    Once you write your constructor signature correctly the answer is easy, just construct the vector with the pack expansion:

    #include 
    
    class GenericNode
    {
    public:
      template
        GenericNode(T*... inputs) : inputs_{ inputs... }
        { }
    private:
        std::vector inputs_;
    };
    

    (You could instead have set it in the constructor body with:

    inputs_ = { inputs... };
    

    but the cool kids use member initializers not assignment in the constructor body.)

    The downside of this solution is that the template constructor accepts any type of pointer arguments, but will then give an error when trying to construct the vector if the arguments aren't convertible to GenericNode*. You could constrain the template to only accept GenericNode pointers, but that's what happens automatically if you do what the other answers suggest and make the constructor take a std::initializer_list, and then you don't need any ugly enable_if SFINAE tricks.

提交回复
热议问题