vendredi 20 juillet 2018

Unpacking variadic template parameters into initializer list

I am currently trying to implement a general initializer to reduce the size of our codebase. At one point however, my code looked like this:

template<typename T, typename Arg1, typename Arg2>
T* ManageDevice(Arg1 arg1, Arg2 arg2)
{
    auto device = new T{ arg1, arg2 };
    // More operations on device
    return device;
}

template<typename T, typename Arg1, typename Arg2, typename Arg3>
T* ManageDevice(Arg1 arg1, Arg2 arg2, Arg3 arg3)
{
    auto device = new T{ arg1, arg2, arg3 };
    // More operations on device
    return device;
}

template<typename T, typename Arg1, typename Arg2, typename Arg3, typename Arg4>
T* ManageDevice(Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4)
{
    auto device = new T{ arg1, arg2, arg3, arg4 };
    // More operations on device
    return device;
}

Which starts to be less elegant. From my understanding, variadic templates seems to be the way to solve this issue. But I don't understand how this can be applied to my situation.

I would prefer something like this:

T* ManageDevice(Args... args)
{
    // The function I want
    // Unpack as a std::initializer_list
    auto allArguments = unpackAll(); 

    auto device = new T{ allArguments };
    // More operations on device
    return device;
}

Any suggestion on how unpackAll() should be implemented? Thanks.

Aucun commentaire:

Enregistrer un commentaire