jeudi 26 octobre 2017

How to create specialized function for tuple elements by their type

I want to write a function that performs an operation on each element of a tuple but it specialized so that if the element is of a certain type, it will do one thing, and if it is of another type, it will do another thing. I have code that can do the same thing on every element:

template<std::size_t I = 0, class ...Ts>
inline typename std::enable_if<I == sizeof...(Ts), void>::type
tupel_el_func(std::tuple<Ts...> &t) { } // base case: do nothing

template<std::size_t I = 0, class... Ts>
inline constexpr typename std::enable_if<I < sizeof...(Ts), void>::type
tupel_el_func(std::tuple<Ts...> &t) {

    auto el = std::get<I>(t);
    // do thing with el
    tupel_el_func<I+1, Ts...>(t);
}

but now I need to specialize this function to do a different thing for elements that are of a certain type (e.g. type char*). I have tried using enable_if like so but it will not compile:

template<int N, typename... Ts>
using NthTypeOf = typename std::tuple_element<N, std::tuple<Ts...>>::type;

template<std::size_t I = 0, class... Ts>
inline constexpr typename std::enable_if<I < sizeof...(Ts) && std::is_same<char*, NthTypeOf<I, Ts...>>::value, void>::type
tupel_el_func(std::tuple<Ts...> &t) {
    // function body for when its a char*
}

template<std::size_t I = 0, class... Ts>
inline constexpr typename std::enable_if<I < sizeof...(Ts) && !std::is_same<char*, NthTypeOf<I, Ts...>>::value, void>::type
tupel_el_func(std::tuple<Ts...> &t) {
    // function body for when it's not a char*
}

Thank you for the help.

Aucun commentaire:

Enregistrer un commentaire