相关疑难解决方法(0)

如何在C++中执行元组运算(c ++ 11/c ++ 17)?

我正在尝试编写模板函数/运算符,例如+在两个相同类型的元组之间进行算术运算.例如,对于

std::tuple<int,double> t = std::make_tuple(1,2);
Run Code Online (Sandbox Code Playgroud)

我想做

auto t1 = t + t;  
Run Code Online (Sandbox Code Playgroud)

逻辑很简单:按顺序进行算术运算.但我无法弄清楚如何在c ++模板编程中完成这项工作(c ++ 11/17).我下面的代码不能编译g++ -std=c++11 tuple_arith.cpp.特别是,我无法弄清楚使用泛型add函数(template<typename T> T add(T x, T y) { return x + y; })来处理元组操作代码的正确方法.

有人可以帮助解释如何解决问题吗?

#include <tuple>

namespace std {
  template<typename _Tp, size_t __i, size_t __size, typename _opT >
     struct __tuple_arith {
       static constexpr _Tp  __op(const _Tp& __t, const _Tp& __u, const _opT& op)  {
         return std::tuple_cat(std::make_tuple(op(std::get<__i>(__t), std::get<__i>(__u))
                               , __tuple_arith<_Tp, __i + 1, __size, _opT>::__op(__t, __u))); …
Run Code Online (Sandbox Code Playgroud)

c++ variadic-templates c++11 stdtuple c++17

5
推荐指数
1
解决办法
693
查看次数

使用std :: get,std :: tuple_size,std :: tuple_element对元组的组件求和

我有一个具有类似元组的界面的自定义类.因为我想我的代码尽可能通用的,我认为这将是我的基础上的功能的算法是一个好主意std::get,std::tuple_size,std::tuple_element所以你只需要专注这些功能用我的算法.让我们称之为需要这些功能特化的概念Tuple.

现在我试图总结一个组件Tuple.函数声明应该是这样的:

template <class Tuple>
int sum_components(const Tuple& t);
Run Code Online (Sandbox Code Playgroud)

我想有很多模板编程涉及但我无法弄清楚如何做到这一点.

对于添加,我只会使用全局的重载+ operator.

我正在使用c ++ 1z.

c++ tuples boost-tuples stdtuple c++17

4
推荐指数
2
解决办法
1335
查看次数

标签 统计

c++ ×2

c++17 ×2

stdtuple ×2

boost-tuples ×1

c++11 ×1

tuples ×1

variadic-templates ×1