Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

C++: How do I make a function run only if the type is a tuple of vectors?

I have the code here online and it works fine: http://paste.ubuntu.com/5793610/

The code is supposed to create a turn a std::tuple of types into a tuple of vectors of those types. Then it's supposed to fill the vectors with numbers and then print the tuple. The only problem I have with it is that theoretically I can pass in a tuple of any types to the printer method but I just want to restrict the implementation of tuple_printer::print to tuples of *vectors*. How would I do that?

I've tried this but it didn't work:

    template <typename... Ts>

    static void print(std::tuple<std::vector<Ts>...>& var, /* ... */)

    {

        // ...

    }

I know why it doesn't work but do you see my intent? How would I be able to do that? Would I need some sort of variadic enable_if implementation that unpacks the parameter pack and checks if each type is a vector? That I would have a hard time doing though. :)

Thanks.

1 Answer

Relevance
  • ?
    Lv 7
    8 years ago
    Favorite Answer

    It's not that hard to make a variadic enable_if that checks if each type is a vector:

    First, make an is_vector type trait:

    template<typename T> struct is_vector : std::false_type {};

    template<typename T> struct is_vector<std::vector<T>> : std::true_type {};

    then, make a helper variadic template metafunction that returns is first (non-variadic) type unchanged

    template<typename T, typename...> using head = T;

    then, unpack your parameter pack into that discarded variadic template argument, enable_if'ing on the way:

    template<typename ...Ts>

    head<void, typename std::enable_if<is_vector<Ts>::value >::type...>

    print(std::tuple<Ts...>& var)

    {

         // ...

    }

Still have questions? Get your answers by asking now.