累积超过元组的值 [英] accumulate over tuple of values
问题描述
我使用元组和模板。我知道如果练习你会使用boost :: fusion(我认为)做这样的事情。我试图实现相当于std :: accumulate在一个元组。
I am playing with tuples and templates. I know if practice you would use boost::fusion (I think) to do this kind of thing. I am trying to implement the equivalent of std::accumulate over a tuple.
下面是我有的代码。就像我可以告诉编译错误是因为它试图使用4模板参数版本,当我打算使用3模板参数版本完成递归。这意味着我错过了一些与函数重载解析。
Below is the code that I have. As near as I can tell the compile error is caused by it trying to use the 4 template parameter version when I intended it to use to the 3 template parameter version to finish recursing. This would imply that I missed something with the function overload resolution.
我曾经认为,因为这两个函数可以匹配,它会选择3模板参数版本作为更好的匹配,因为显式声明了最后一个参数类型。我仍然得到相同的行为,如果我添加std :: tuple_size作为额外的模板参数到两个版本的tuple_accumulate_helper。
I had thought that since both functions could be matched that it would pick the 3 template parameter version as being the better match since the last parameter type is explicitly stated. I still get the same behavior if I add std::tuple_size as an additional template parameter to both versions of tuple_accumulate_helper.
任何人都可以建议我做错了什么? p>
Can anyone suggest what I am doing wrong?
#include <tuple>
template <std::size_t I>
struct int_{};
template <typename T, typename OutT, typename OpT, std::size_t IndexI>
auto tuple_accumulate_helper(T tuple, OutT init, OpT op, int_<IndexI>) -> decltype(tuple_accumulate_helper(tuple, op(init, std::get<IndexI>(tuple)), op, int_<IndexI + 1>()))
{
return tuple_accumulate_helper(tuple, op(init, std::get<IndexI>(tuple)), op, int_<IndexI + 1>());
}
template <typename T, typename OutT, typename OpT>
auto tuple_accumulate_helper(T tuple, OutT init, OpT op, int_<std::tuple_size<T>::value>) -> decltype(init)
{
return init;
}
template <typename T, typename OutT, typename OpT>
auto tuple_accumulate(T tuple, OutT init, OpT op) -> decltype(tuple_accumulate_helper(tuple, init, op, int_<0>()))
{
return tuple_accumulate_helper(tuple, init, op, int_<0>());
}
struct functor
{
template <typename T1, typename T2>
auto operator()(T1 t1, T2 t2) -> decltype(t1 + t2)
{
return t1 + t2;
}
};
int main(int argc, const char* argv[])
{
auto val = tuple_accumulate(std::make_tuple(5, 3.2, 7, 6.4f), 0, functor());
return 0;
}
推荐答案
你有兴趣,但如果你可以使用一点点提升,你可以有这个开箱即用:
I don't know if you're interested, but if you can use a little boost, you can have this "out of the box":
#include <boost/fusion/adapted/std_tuple.hpp>
#include <boost/fusion/include/algorithm.hpp>
#include <boost/phoenix/phoenix.hpp>
using namespace boost::phoenix::arg_names;
#include <iostream>
int main()
{
auto t = std::make_tuple(5, 3.2, 7, 6.4f);
std::cout << boost::fusion::accumulate(t, 0, arg1 + arg2) << std::endl;
std::cout << boost::fusion::accumulate(t, 1, arg1 * arg2) << std::endl;
}
列印
21.6
716.8
这篇关于累积超过元组的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!