In C++11 or C++14, I'm trying to define a type alias to a constexpr function.
I tried:
#include <iostream>
constexpr int foo(int i, int j) { return i + j; }
using TConstExprFunction = constexpr int (*)(int i, int j);
int main() {
TConstExprFunction f = foo;
constexpr int i = f(1, 2);
std::cout << i << std::endl;
}
But it fails to compile with g++ and clang++.
g++:
error: expected type-specifier before 'constexpr'
clang++:
error: type name does not allow constexpr specifier to be specified
I have to do as below to make it compile
#include <iostream>
constexpr int foo(int i, int j) { return i + j; }
using TConstExprFunction = int (*)(int i, int j);
int main() {
constexpr TConstExprFunction f = foo;
constexpr int i = f(1, 2);
std::cout << i << std::endl;
}
From clang++'s error message, it seems I can NOT using constexpr
for type name.
So, is it possible to define a type alias to a constexpr function; If yes, how?
A const int var can be dynamically set to a value at runtime and once it is set to that value, it can no longer be changed. A constexpr int var cannot be dynamically set at runtime, but rather, at compile time. And once it is set to that value, it can no longer be changed.
A call to a constexpr function produces the same result as a call to an equivalent non- constexpr function , except that a call to a constexpr function can appear in a constant expression. The main function cannot be declared with the constexpr specifier.
Short answer: static_assert(false) should never appear in a constexpr if expression, regardless of whether it's in a template function or whether it's in the discarded branch.
According to the C++ standard 7.1.5/p8 The constexpr
specifier [dcl.constexpr] (Emphasis Mine):
The
constexpr
specifier has no effect on the type of aconstexpr
function or aconstexpr
constructor.
Also from 7 Declarations [dcl.dcl]:
alias-declaration: using identifier attribute-specifier-seqopt = defining-type-id ;
constexpr
specifier is not part of a function's type. Consequently, you can't do:
using TConstExprFunction = constexpr int (*)(int i, int j);
Since after a using TConstExprFunction =
a type is expected.
You cannot define a type alias to a constexpr function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With