For example I got this code:
constexpr static std::size_t ConstexprFunction(const int value) {
return value;
}
static constexpr std::size_t CallConstexptrFunction(const int value) {
constexpr std::size_t v = ConstexprFunction(value);
return v;
}
int main() {
constexpr int test = 42;
CallConstexptrFunction(test);
}
the compiler will argued that constexpr variable 'v' must be initialized by a constant expression
, it looks like the ConstexprFunction
is actually run on runtime, not on compile-time. I change the code to this:
static constexpr std::size_t CallConstexptrFunction(const int value) {
constexpr std::size_t v = value;
return v;
}
int main() {
constexpr int test = 42;
CallConstexptrFunction(test);
}
and the error keeps the same, which may prove that when use the value
in the CallConstexptrFunction
, it is considered to a runtime variable rather than a contexpr
variable.
currently my solution is to change the function parameter to a template parameter to avoid parameter passing:
constexpr static std::size_t ConstexprFunction(const int value) {
return value;
}
template<int SIZE>
static constexpr std::size_t CallConstexptrFunction() {
constexpr std::size_t v = ConstexprFunction(SIZE);
return v;
}
there's a similarly question, but the question:
- It is based on C++11.
- One of the OP's solution makes the function run on runtime, don't know the OP award that or not (the case he called the returned the function directly, not hold the return value by a constexpr variable).
and after reading the question here's my questions:
- Will the template version generate too many instances which will lead the code size to be too large?
- Can the function parameter passing be done without using template (any version is welcome, even C++20), I tried
constexpr int value
as parameter and use Clang and C++20 experimental, it seems this syntax is still not allowed.