如何初始化div_t对象? [英] How can I Initialize a div_t Object?
问题描述
因此,从 div
函数似乎是实现定义的.
So the order of the members returned from the div
functions seems to be implementation defined.
quot
是1 st 成员还是rem
?
让我们说我正在做这样的事情:
Let's say that I'm doing something like this:
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
是唯一的跨平台方法吗?
Of course the problem here is that I don't know if I initialized i.quot
or i.rem
in my lambda capture. Is intializing i
with div(quot, 1)
the only cross platform way to do this?
推荐答案
我认为VS解决方法可能如下所示:
I think the VS workaround could look like this:
#include <cstdlib>
#include <type_traits>
template<class T>
struct DTMaker {
using D = decltype(div(T{}, T{}));
static constexpr D dt = D{0,1};
static constexpr auto quot = dt.quot;
};
template <class T, typename std::enable_if<DTMaker<T>::quot == 0>::type* = nullptr>
typename DTMaker<T>::D make_div(const T ", const T& rem) { return {quot, rem}; }
template <class T, typename std::enable_if<DTMaker<T>::quot == 1>::type* = nullptr>
typename DTMaker<T>::D make_div(const T ", const T &rem) { return {rem, qout}; }
int main() {
div_t d_t = make_div(1, 2);
}
如果您使用的是c ++ 17,则还可以尝试使用结构化绑定,constexpr函数和SFINAE重载来检测首先在结构中声明哪个字段:
If you are using c++17 you could also try to use structured binding, constexpr function and SFINAE overloading to detect which field is declared first in the structure:
#include <cstdlib>
#include <algorithm>
#include <iterator>
constexpr bool first_quot() {
auto [x, y] = std::div_t{1, 0};
(void)y;
return x;
}
template <bool B = first_quot()>
std::enable_if_t<B, std::div_t> foo() {
int quot = 1;
int rem = 0;
return {quot, rem};
}
template <bool B = first_quot()>
std::enable_if_t<!B, std::div_t> foo() {
int quot = 1;
int rem = 0;
return {rem, quot};
}
int main() {
foo();
}
或更简单的使用constexpr:
Or even simpler use if constexpr:
#include <cstdlib>
#include <algorithm>
#include <iterator>
constexpr bool first_quot() {
auto [x, y] = std::div_t{1, 0};
(void)y;
return x;
}
std::div_t foo() {
int quot = 1;
int rem = 0;
if constexpr(first_quot())
return {quot, rem};
else
return {rem, quot};
}
int main() {
foo();
}
这篇关于如何初始化div_t对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!