具有交替类型的变量模板参数包 [英] Variadic Template Parameter Packs with Alternating Types
问题描述
我想知道是否可以使用参数包捕获交替的参数模式。例如,
I was wondering if it is possible to capture an alternating parameter pattern using a parameter pack. For example,
template<typename T, size_t U, typename... Args>
class foo<T, U, Args...>
{
public:
foo() : my_T(nullptr), my_U(U) {}
private:
T* my_T;
size_t my_U;
foo<Args...> my_next_foo;
}
所以这不工作,因为Args是一个只有类型的参数包。有没有办法修改这个,使类型名T,size_t U模式可以在一个可变参数模板中正确捕获?感谢
So this doesn't work since Args is a parameter pack of only types. Is there a way to modify this so that the typename T, size_t U pattern can be properly captured in a variadic template? Thanks
推荐答案
根据我的经验,作为模板参数的值是二等公民。
Values as template parameters are second class citizens, in my experience.
使用别名将其升级为第一类:
Upgrade them to first class with an alias:
template<std::size_t n>
using size = std::integral_constant<std::size_t, n>;
然后模式匹配:
template<class...>
struct foo;
template<>
struct foo<> {
// empty
};
template<class T, size_t U, typename... Args>
struct foo<T, size<U>, Args...> {
foo() : my_T(nullptr), my_U(U) {}
private:
T* my_T;
size_t my_U;
foo<Args...> my_next_foo;
};
bob是您的叔叔。
请注意,以 U
作为模板参数,然后将其存储为运行时值,是非常有问题的。
Note, however, that taking U
as a template parameter, then storing it as a run time value, is highly questionable.
foo
的用户必须:
foo< Chicken, size<3>, Dog, size<17> >
而不是
foo< Chicken, 3, Dog, 17 >
这篇关于具有交替类型的变量模板参数包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!