mercredi 21 juillet 2021

How can I "generate" template spezialations for a function from a variadic template argument?

I think I will first show the example and then explain it:

#include <array>

template<typename T_, size_t size_>
struct arg
{
    using T = T_;
    static constexpr size_t size = size_;
};

template<typename... Arugments>
struct Foo
{
    template<typename Argument>
    std::array<typename Argument::T, Argument::size>& getArray() // specializations of all args in Arguments should be generated
    {
        static std::array<typename Argument::T, Argument::size> arr;
        return arr;
    }
};

int main()
{
    Foo<arg<int, 10>, arg<float, 10>, arg<float, 1>> myFoo;
    myFoo.getArray<arg<int, 10>>();
    myFoo.getArray<arg<float, 10>>(); // should return a different array than the line above
    myFoo.getArray<arg<bool, 1>>(); // should NOT work because arg<bool, 10> is was not passed to Foo
}

If got a struct arg which contains the information how to construct arr in getArray. A list of args is passed to Foo. Now I want that template specializations of getArray to be generated for each arg in Arguments. If no specialization was generated for a specific arg I want that some kind of error occurs.

How could I achieve this?

Aucun commentaire:

Enregistrer un commentaire