所以从 div
返回的成员顺序函数似乎是实现定义的。
quot
是第 1 个 成员还是 rem
?
假设我正在做这样的事情:
generate(begin(digits), end(digits), [i = div_t{ quot, 0 }]() mutable {
i = div(i.quot, 10);
return i.rem;
})
当然这里的问题是我不知道我是否在我的 lambda 捕获中初始化了 i.quot
或 i.rem
。使用 div(quot, 1)
初始化 i
是唯一的跨平台方式吗?
最佳答案
你是对的,成员的顺序是未指定的。该定义是从 C 继承的,它明确指出它是(强调我的):
7.20.6.2 The div, ldiv, and lldiv functions
3 [...] The structures shall contain (in either order) the members
quot
(the quotient) andrem
(the remainder), each of which has the same type as the argumentsnumer
anddenom
. [...]
在 C 中,未指定顺序这一事实无关紧要,并且包含一个专门针对 div_t
的示例:
6.7.8 Initialization
34 EXAMPLE 10 Structure members can be initialized to nonzero values without depending on their order:
div_t answer = { .quot = 2, .rem = -1 };
不幸的是,C++ 从未采用这种语法。
我可能会在辅助函数中进行简单赋值:
div_t make_div_t(int quot, int rem) {
div_t result;
result.quot = quot;
result.rem = rem;
return result;
}
对于普通的 int
值,无论您使用初始化还是赋值并不重要,它们具有相同的效果。
除以 1
也是一个有效选项。
关于c++ - 如何初始化一个 div_t 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41556257/