Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variadic templates type traits resolution

Assume I have an enum, and I want each enum value to be associated with a certain type. Say the standard type is double, and if I want it to be something else I need to specify it explicitly.

Q1: Is this the preferred way to implement such a thing?

enum A {
    v1,
    v2,
    v3
};

// for every value of A, the standard type is double
template<A a>
struct A_info {
    typedef double type;
};

// other types for certain values can be specified using specialization
template<>
struct A_info<v2> {
    typedef size_t type;
};

Then, assume I have some function template, and I want to call the function depending on the type associated with a value of the enum:

template<typename T>
void foo() { /* do something */ }

template<A a>
void bar() { 
    foo< typename A_info<a>::type >(); 
}

This works fine. Now assume, I have another function depending on a variadic template list, and I want to do something similar as above ...

template<typename ... T>
void foo_multiple() { /* stuff */ }

template<A ... a>
void bar_multiple() {  
    foo_multiple< /* ??? */ > ();
}

Q2: How to implement this? Is this possible, anyway?

like image 414
fdlm Avatar asked Feb 20 '23 20:02

fdlm


1 Answers

Just expand the variadic parameter pack with the pattern you want:

template<A ... a>
void bar_multiple() {  
    foo_multiple<typename A_info<a>::type...> ();
}
like image 141
R. Martinho Fernandes Avatar answered Mar 04 '23 10:03

R. Martinho Fernandes