c++ - 累加值元组

标签 c++ c++11

我在玩元组和模板。我知道如果练习你会使用 boost::fusion(我认为)来做这种事情。我正在尝试在元组上实现 std::accumulate 的等价物。

下面是我的代码。据我所知,编译错误是由于它在我打算使用 3 模板参数版本来完成递归时尝试使用 4 模板参数版本引起的。这意味着我错过了函数重载决议的某些内容。

我曾认为,由于两个函数都可以匹配,所以它会选择 3 模板参数版本作为更好的匹配,因为最后一个参数类型已明确说明。如果我将 std::tuple_size 作为附加模板参数添加到两个版本的 tuple_accumulate_helper,我仍然会得到相同的行为。

谁能指出我做错了什么?

#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;
}

最佳答案

我不知道你是否有兴趣,但如果你可以使用一点提升,你可以“开箱即用”:

#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

关于c++ - 累加值元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17735938/

相关文章:

c++ - 缺少预期的对象构造

c++ - 编译器忽略我的包含 -I 新库版本

C++ 从具有取消引用类型类型的函数返回引用?

c++ - 'If Else' 语句缩进在 C++ 中重要还是不重要?

c++ - [=] 在 C++ 中是什么意思?

c++ - C++0x 中的 disable_if 在哪里?

c++ - 如何将 std::string 转换为 boost::chrono::nanoseconds

c++ - __try 和 __except 在发布版本中不起作用

c++ - 从不兼容类型 'int' 分配给 [custom typdef]

c++ - 如何在编译时将 C 字符串转换为 int?