[英]Obtain types of variadic types in template template classes
假设我们有一堂课
template <int ... values>
struct foo;
现在我有一个功能
template<typename foo_type, typename U>
void bar(foo_type a, U b);
其中foo_type
基本上是foo
。 我的问题是,我不需要bar
函数中的变量a
。 我希望能够像这样调用该函数
bar<foo<6,5,7,8,0>>(42);
但是在bar
可以使用foo
所有参数。 我尝试将功能更改为
template<template<int...> class foo_type, int ... args, typename U>
void bar(U b)
但这根本行不通。 我怎样才能做到这一点? 如何将bar
更改为上述方式,并且仍然可以访问foo
的参数? 基本上我想在运行时对这些列表进行通用计算
// within the body of bar
constexpr int[sizeof...(args)] = {args...};
其中args
是foo
参数。
您反对foo
作为参数有多反对? 就个人而言,我喜欢让一切成为争论。 只需将其包装为空类型即可:
template <class T> struct tag_type { using type = T; };
template <class T> constexpr tag_type<T> tag{};
这样您仍然可以在ints...
上进行模板ints...
:
template<int... Is, typename U>
void bar(tag_type<foo<Is...>> a, U b) {
constexpr int stuff[sizeof...(Is)] = {Is...};
// ...
}
而不是调用bar<foo<6,5,7,8,0>>(42);
你会打电话给bar(tag<foo<6,5,7,8,0>>, 42);
,它足够接近。
要获得所需的确切信息,可以将前一个呼叫转发给后者:
namespace details {
template<int... Is, typename U>
void bar(tag_type<foo<Is...>> a, U b) {
constexpr int stuff[sizeof...(Is)] = {Is...};
// ...
}
}
template <typename foo_type, typename U>
void bar(U b) {
details::bar(tag<foo_type>, b);
}
现在,这是两全其美。
我相信,问题是关于从给定的foo
类型中提取模板参数? 如果我是正确的,这是解决方案。
您将需要部分专门化一个助手类,如下所示:
template <int ... values>
struct foo { };
template<class T>
struct bar_helper {};
template<int... values> struct bar_helper<foo<values...> > {
template<class T> static void bar(T ) {
// Use values... here
}
};
template<class foo_type, class U>
void bar(U b) {
bar_helper<foo_type>::bar(b);
}
void check() {
bar<foo<2, 3, 4, 5, 6> >(42);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.