c++ - 来自单个整数参数的可变模板声明?
问题描述
是否可以从单个整数类型模板参数静态声明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 实现来解析单个整数模板参数,因为语法会更简洁和直观。
解决方案
一种可能的解决方案,使用元组和帮助模板来组装所需的类。一点额外的糖可以使生成的语法“更干净” 用 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;
}
推荐阅读
- gradle - Gradle jlink 选项给出访问权限警告
- sql - 使用循环 postgres 更新表数据
- list - 我需要存储为地理位置列表的道路数据
- r - ggplot2 中 PCA 分数的 Facetgrid
- python-3.x - 在 Tensorboard 中使用 Tensorflow v2.0 显示图形
- javascript - 页面未使用本地存储更新
- wordpress - add_filter() 中的函数永远不会运行
- python - 将值添加到序列化字典而不加载它
- javascript - 选择 id 并显示名称
- laravel - 在 Laravel 中更新时检查第 1 列和第 2 列的值是否不等于其他行