首页 > 解决方案 > 来自单个整数参数的可变模板声明?

问题描述

是否可以从单个整数类型模板参数静态声明N个相同类型的模板参数?可能与此类似:

template < int N >
class MyTemplatedType {
    // base type, known
    typedef float base_t;
    // instance of some other templated class with *N* template arguments
    SomeOtherClass< base_t, base_t, base_t, base_t, ..., base_t > foo;
    /* ... */
}

我知道我可以使用可变参数模板并将其直接用于成员实例声明,但我想知道是否会有某种 SFINAE 实现来解析单个整数模板参数,因为语法会更简洁和直观。

标签: c++templatessfinaevariadic

解决方案


一种可能的解决方案,使用元组和帮助模板来组装所需的类。一点额外的糖可以使生成的语法“更干净” 用 gcc 10.2 测试:

#include <tuple>
#include <type_traits>

// Create std::tuple<T ...>, with T repeated N times.

template<int N, typename T>
struct tuple_list : tuple_list<N-1, T> {

    typedef decltype(std::tuple_cat(std::declval<typename tuple_list<N-1, T>
                    ::tuple_t>(),
                    std::declval<std::tuple<T> &&>())
             ) tuple_t;
};

template<typename T>
struct tuple_list<0, T> {

    typedef std::tuple<> tuple_t;
};

template<typename ...> struct SomeOtherClass {};

// And now, replace `std::tuple` with SomeOtherClass 

template<typename tuple_t> struct make_some_other_class;

template<typename ...Args>
struct make_some_other_class<std::tuple<Args...>> {

    typedef SomeOtherClass<Args...> type_t;
};

template < int N >
class MyTemplatedType {

    typedef float base_t;

public:

    // The payload is not exactly "clean", but one more helper
    // template can make the syntax here a little bit nicer...

    typename make_some_other_class< typename tuple_list<N, base_t>
                    ::tuple_t >::type_t foo;
};

void foobar(MyTemplatedType<3> &bar)
{
    SomeOtherClass<float, float, float> &this_works=bar.foo;
}

推荐阅读