Search code examples
c++constructorintegervariadic-templates

Is it possible to write variadic template constructor initializing all members of a class/struct?


Is it possible to achieve this:

struct S
{
    int a;
    std::string s;

    template<typename... Args>
    S(Args... args)
    :  // what next?
    {
        // what next?
    }
};

Or is there any other way to achieve (something like) this? (std::tuple?)


Solution

  • You can use std::tie to create tuple of lvalue references to your data members, and assign content of another tuple created based on passed arguments:

    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
    

    Demo