c++ - 对或元组值的名称别名引用

标签 c++ c++17 std-pair stdtuple structured-bindings

在重构某些代码时,我在返回具有 2 个值的结构时遇到了“问题”。现在这些真的应该以记录的效果命名。后来我想使用 tie 所以我将结构更改为继承自 std::pair 并设置引用。现在这实际上工作正常,但你会注意到现在我的结构的大小为 24,而不是与这对结构相比只有 8。

#include <tuple>


struct Transaction : public std::pair<int, int> {
    using pair::pair;

  int& deducted = first;
  int& transfered = second;
};
//static_assert(sizeof(Transaction) == sizeof(std::pair<int, int>));//commenting in this line will fail compilation

Transaction makeTheTransaction();

void test(int& deduct, int& transfer) {
    std::tie(deduct, transfer) = makeTheTransaction(); 
}

可能显而易见的方法是更改​​为成员函数,但是对于这种情况来说,这也是太多的“样板”(这样以后不使用 tie 就变得更容易了)。一个直接的 memcpy 是例如。元组是直截了当的 UB。直接结构化绑定(bind)也不可行,因为变量已在使用中。

我的问题是什么是忽略可重用部分的更好或最小代码解决方案(并且考虑到大小不应超过 2 个整数的大小)?

更新:对于这种情况,我最终只是做了一个简单的结构并暂时保留返回值。对于来到这里的其他用户,有一个 boost 库提案似乎能够将任何结构转换为元组:https://github.com/apolukhin/magic_get/

最佳答案

看来你把问题复杂化了。如果你需要使用std::tie,你可以直接使用它。无需更改您的结构:

struct Transaction
{
  int deducted;
  int transferred;
};

// later...

auto t = std::tie(transaction.deducted, transaction.transferred);

如果这是你经常使用的模式,那么你可以将它包装在一个小的辅助方法中:

struct Transaction
{
  int deducted;
  int transferred;

  auto to_tuple() const
  {
    return std::tie(deducted, transferred);
  }
};

您也可以使用它一次分配给多个变量,但我强烈反对这样做。它容易出错并导致代码脆弱。 (例如,如果您在下面的示例中颠倒了 deducttransfer 的顺序,就会出现错误,但编译器不会给出警告或错误。)

void test(int& deduct, int& transfer)
{
  std::tie(deduct, transfer) = makeTheTransaction().to_tuple();
}

编辑:再三考虑......

如果这里的目标只是简单地将结构分解为变量,您可以直接这样做并避免使用对或元组:

struct Transaction
{
  int deducted;
  int transferred;

  void decompose(int* deducted_, int* transferred_)
  {
    *deducted_ = deducted;
    *transferred_ = transferred;
  }
};

void test(int& deduct, int& transfer)
{
  makeTheTransaction().decompose(&deduct, &transfer);
}

这仍然很脆弱,但至少现在,当您编写对 decompose 方法的调用时,您将获得智能感知,这将使模式不太容易出错。

关于c++ - 对或元组值的名称别名引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53400051/

相关文章:

c++ - 在 Linux 上创建原子文件?

c++ - 如何通过键有效地合并 k 个排序的成对键/值 vector ?

c++ - 替代宏以帮助类型安全和减少重复

c++ - 如何从参数包构造引用的 std::tuple?

c++ - std::map 字符串到 boost::thread_specific_ptr

android - OpenGL fragment 着色器正在移动对象

c++ - C 中 OpenMP 并行编程的性能

c++ - 编译使用 spidermonkey 的程序时出现链接器错误

c++ - STL图插入效率: [] vs.插入

java - Swig java 进程 std::pair 与 c++ 中的类