问题
I wonder if, for example, evaluated compiled on a little endian platform will return true on a big endian target platform.
constexpr bool is_little_endian()
{
int num = 1;
return (1 == *(char *)&num);
}
In other words, are constexpr evaluated as if on the target?
EDIT: This example isn't correct, but the question is still active.
回答1:
First off: If you compile code for a given target, then the compiler will generate code for that target. This, of course, includes expressions that are evaluated at compile-time - otherwise every cross compilation that involved such expressions would be broken.
However, just marking a function as constexpr
does not guarantee that it is evaluated at compile-time. In particular, your sample function cannot (according to the standard) be evaluated at compile-time, so it is orthogonal to the primary question.
As remarked in the comments, you can't really find out endianness at compile-time without querying the compiler directly. The compiler has to know (because it has to generate code) and any reasonable compiler will provide a way for you to query this information (at compile-time).
回答2:
This is not a valid constexpr
function as it has reinterpret_cast
baked into it. This makes the whole question moot.
And the reason why this is not valid constexpr function is outlined here: https://en.cppreference.com/w/cpp/language/constexpr. In particular, constexpr function should satisfy, among others, following criteria:
...there exists at least one set of argument values such that an invocation of the function could be an evaluated subexpression of a core constant expression
reinterpret_cast
can never be a part of core constant expression.
回答3:
Yes they are. If you have a C++20 compiler available (probably -std=c++2a
) you can try to compile this for platforms with different endianess and see that it behaves correctly.
#include <bit>
#include <iostream>
constexpr bool are_all_scalar_types_little_endian() {
return std::endian::native == std::endian::little;
}
constexpr bool are_all_scalar_types_big_endian() {
return std::endian::native == std::endian::big;
}
int main() {
std::cout << std::boolalpha
<< "little: " << are_all_scalar_types_little_endian() << '\n'
<< "big : " << are_all_scalar_types_big_endian() << '\n'
<< "mixed : " <<
(are_all_scalar_types_little_endian()==are_all_scalar_types_big_endian()) << '\n';
}
来源:https://stackoverflow.com/questions/53502973/are-constexpr-evaluated-on-target-platform