【发布时间】:2013-01-30 04:06:29
【问题描述】:
作为练习,我正在尝试编写 2 个采用非类型模板 int N 的简单函数。 第一个需要创建一个由 T 类型对象的 N 个副本组成的元组。我希望它类似于以下内容:
template <class T, int N>
constexpr std::tuple<T...> fun(T t) {
return (N > 0) ? std::tuple_cat(t, fun<T, N-1>(t)) : std::make_tuple(t);
}
我也尝试过这样的事情,但没有成功 (http://liveworkspace.org/code/3LZ0Fe)。 我希望能够用 T = bool 来实例化它,比如:
auto bools = fun<bool, 10> (false);
第二个应该是轻微的变化;我有一个模板结构 Foo,我想创建一个包含 Foo, ..., Foo
的元组template <int N> struct Foo {
static const int id = N;
}
template <template <int> class T, int N>
constexpr ??? fun2 (???) {...}
由于模板函数不能部分特化,我什至不知道如何为我的递归编写适当的终止。 我想完全静态地做到这一点,而不使用 for 循环。
================================================ ====================================
按照 Seth 的建议,我一直坚持编写无限递归的 fun 函数本身:
template<typename T, int N>
typename fun_helper<T, N>::type
fun(T t) {
if (N > 0)
return typename fun_helper<T, N>::type
{ std::tuple_cat(std::make_tuple(t), fun<T, N-1>(t)) };
else return typename fun_helper<T, N>::type { };
}
通过使用带有终止的附加结构,我能够得到这个工作:
template<typename T, int N> struct fun {
typename fun_helper<T, N>::type make(T t) {
return typename fun_helper<T, N>::type
{ std::tuple_cat(std::make_tuple(t), fun<T, N-1>().make(t)) };
}
};
template<typename T> struct fun<T, 0> {
typename fun_helper<T, 0>::type
make(T t) {
return typename fun_helper<T, 0>::type { };
}
};
调用还是比较笨拙:
auto conds = fun<bool, 3>().make(false);
有没有办法让它在没有这个额外的结构的情况下工作?
auto conds = fun<bool, 3>(false);
【问题讨论】:
标签: c++ tuples variadic-templates