lundi 24 août 2015

Defining all the arguments with one template

Suppose this simple example

template <std::size_t> struct FooReturnType;

template <> struct FooReturnType<0> { using type = int; };
template <> struct FooReturnType<1> { using type = char; };

template <std::size_t N> typename FooReturnType<N>::type foo(int);

template <> int foo<0>(int) {return 5;}
template <> char foo<1>(int) {return 'c';}

were changed to foo arguments int foo<0>(int, char) and char foo<1>(double, long). Then we could do something like:

#include <iostream>
#include <tuple>

template <std::size_t> struct FooReturnType;

template <> struct FooReturnType<0> { using type = int; };
template <> struct FooReturnType<1> { using type = char; };

template <std::size_t> struct FooArguments;

template <> struct FooArguments<0> {
    using type = std::tuple<int, char>;
};

template <> struct FooArguments<1> {
    using type = std::tuple<double, long>;
};

template <std::size_t N>
typename FooReturnType<N>::type
    foo(typename std::tuple_element<0, typename FooArguments<N>::type>::type,
        typename std::tuple_element<1, typename FooArguments<N>::type>::type
    );

template <> int foo<0>(int, char) {return 5;}
template <> char foo<1>(double, long) {return 'c';}

int main() {
    std::cout << foo<0>(3,'b') << '\n';  // 5
    std::cout << foo<1>(5.2, 1000) << '\n';  // c
}

But now what if the arguments of foo<N> were not all of the same length? For example, let's have char foo<1>(double, long, bool) instead. Then we need for forward declare foo with something like

typename FooReturnType<N>::type foo (typename std::tuple_element<Is, Tuple>::type...);

But how do we do that?

Aucun commentaire:

Enregistrer un commentaire