【发布时间】:2018-11-20 19:19:02
【问题描述】:
在重组一些代码时,我在返回具有 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。直接结构化绑定也不可行,因为变量已在使用中。
我的问题是,不考虑可重用部分(并且考虑到大小不应超过 2 个整数),什么是更好或最少的代码解决方案?
更新:对于这种情况,我最终只是做了一个简单的结构并暂时保留返回。对于来到这里的其他用户,有一个库提案来提升似乎能够将任何结构转换为元组:https://github.com/apolukhin/magic_get/
【问题讨论】:
-
简单:
struct Transaction {int deducted; int transfered; };? -
@Jarod42 可以,但它无法记录
makeTheTransaction()返回的内容。 -
为什么你必须从 std::pair 继承?您可以只让 makeTransaction 返回一个普通的旧对,因为您似乎没有使用“扣除”和“转移”字段(这不会像所写的那样工作,需要在构造函数中设置引用) .
-
继承 std::pair 是 UB。
-
我不明白为什么你需要从
std::pair继承才能使用std::tie。只需使用它:auto t = std::tie(transaction.deducted, transaction.transferred).
标签: c++ c++17 std-pair stdtuple structured-bindings