Reputation: 103
To force the evaluation of a constexpr
function at compile time, I should be
able to assign its return value to a constexpr
variable.
constexpr bool const_d_ref(const double& v) { return false; }
int main() {
constexpr double dd = 0.0;
constexpr bool cb = const_d_ref(dd);
}
This seems to work fine with g++
and clang++
.
In order to hide the constexpr
from the consumer, I move the actual function
definition into the namespace detail
, create a new function which assigns the
return value to a constexpr
variable and return it.
namespace detail {
constexpr bool const_d_ref(const double& v) { return false; }
}
constexpr bool const_d_ref(const double& v) {
constexpr bool b = detail::const_d_ref(v);
return b;
}
int main() {
constexpr double dd = 0.0;
bool b = const_t_ref(dd);
constexpr bool cb = detail::const_t_ref(dd);
}
It works as expected with g++
, but clang++
returns a compiler error:
error: constexpr variable 'b' must be initialized by a constant expression
Is what I'm doing allowed? Or is clang
being to restrictive? Or is gcc
being to permissive?
cpp.godbolt.org: gcc 6.1 & clang 3.8
Upvotes: 2
Views: 1990
Reputation: 218700
v
in constexpr bool const_d_ref(const double& v) {
is not a compile-time expression. Therefore detail::const_d_ref(v)
is also not a compile-time expression.
Your example will work if you change b
to const
:
const bool b = detail::const_d_ref(v);
Upvotes: 5