具有混合类型参数和非类型可变参数的模板模板参数

时间:2019-05-16 02:54:01

标签: c++ templates c++17 variadic-templates generic-programming

我在声明以下内容时遇到了麻烦:

// c++17
template<typename T, typename ...Before, T v, typename ...After, template<typename ..., T, typename ...> U>
auto enum_to_type() {
    // do things with
    // U<Before..., v, After...> obj;
    // as an example:
    return U<Before..., v + 1, After...>{};
}

// demonstrate of usage

template<int v>
struct A {};

template<typename T, int v>
struct B {};

/// call enum_to_type to get next type
/// note: the following does not compile
using next_A = decltype(enum_to_type<int, 0, A>()); 
// == A<1>
template<typename T>
using next_B = decltype(enum_to_type<int, T, 0, B>()); 
// == B<1>


此函数的目的是编写通用代码,该代码可以利用非类型模板参数v从类模板U构造模板类,而无需知道如何声明模板参数在U中。否则,必须为不同的签名(例如U<T v>U<typename, T v>U<T v, typename>等)编写此功能。

编辑:我想我想要的可能是不可能的。

1 个答案:

答案 0 :(得分:2)

可以进行一些修改:

//type container template
template<typename...>
struct types{};
//declaration
template<typename ,auto V, typename, template<typename ,decltype(V), typename...>class>
class enum_to_type;
//generic definition
template<typename First, typename ... Befors, First V, typename ... Afters, template<typename ,First, typename...>class U>
class enum_to_type<types<First, Befors...>, V, types<Afters...>, U>{
public:
    static auto go(){
        return U<types<Befors...>, V + 1, Afters...>{};
    }
};
//specialization
template<auto V, typename ... Afters, template<typename ,decltype(V), typename...>class U>
class enum_to_type<types<>, V,types<Afters...>, U>{
public:
    static auto go(){
        return U<types<>, V + 1, Afters...>{};
        //or
        //return U<types<>, V, Afters...>{};
    }
};
//Declarations and specializations for the target class templates
template<typename, int>
struct A{};

template<typename, int, typename>
struct B;
template<typename T, int V>
struct B<types<>, V, T > {};

using next_A = decltype(enum_to_type<types<int>,  0, types<>, A>::go());

template<typename T>
using next_B = decltype(enum_to_type<types<int>, 0, types<T>, B>());

template<typename, auto, typename...>
struct general_case;
template<typename ... befors, int V, typename ... afters>
struct general_case<types<befors...>, V, afters ...> {};

用法:

decltype(enum_to_type<types<>,  0, types<>, A>::go()) object_A;
decltype(enum_to_type<types<>, 0, types<int>, B>::go()) object_B;
decltype(enum_to_type<types<int, float>, 3, types<int>, general_case>::go()) object_general;

只是编译器没有办法找出前后有多少种类型。这就是为什么在模板声明中通常只能使用一个参数包的原因。但是它可以专门处理多个参数包!

祝你好运!