Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to strip a tuple of pairs to variadic template types or instantiat something with variadic types?

Tags:

c++

c++11

I have a tuple of pairs in which each pair has a fixed type and a variant type. What I want is a list of the variant types or defining an object (which definitely constructs with a variadic template pack) with these types.

According to How do I strip a tuple<> back into a variadic template list of types?, it is possible to instantiate something with constituent types of the tuple. But in this case, I don't know whether it is even possible and if possible, how to do it.

Imagine I have something like this:

struct MyFixedType
{ /* ... */ };


using Tuple = std::tuple<
    std::pair<MyFixedType, int>,
    std::pair<MyFixedType, double>,
    std::pair<MyFixedType, std::string>
>;

And I have this class:

template <typename... Ts>
class MyClass
{
};

What I want is to declare an object of MyClass with <int, double, std::string>

Note: Although this case can be handled using a pre-processor or some macros, I'm not allowed to use macros.

like image 655
rezaebrh Avatar asked Oct 27 '22 09:10

rezaebrh


1 Answers

Using function template argument deduction for brevity:

template <class Fixed, class... Variant>
MyClass<Variant...> MyClassFromPairTuple_impl(std::tuple<std::pair<Fixed, Variant>...> &&);

template <class Tuple>
using MyClassFromPairTuple = decltype(MyClassFromPairTuple_impl(std::declval<Tuple>()));

Usage:

using Tuple = std::tuple<std::pair<MyFixedType, int>, std::pair<MyFixedType, double>, std::pair<MyFixedType, std::string>>;

MyClassFromPairTuple<Tuple> instance; // MyClass<int, double, std::string>

Live demo

like image 119
Quentin Avatar answered Oct 31 '22 08:10

Quentin