constexpr int get () { return 5; }
template<int N> struct Test {};
int main ()
{
int a[get()]; // ok
Test< get() > obj; // error:'int get()' cannot appear in a constant-expression
}
I have compiled this code with ideone. And was wondering that why it's giving compilation error.
Is constexpr
function not allowed as template
argument or it's a bug in the compiler ?
Edit: changed const int get()
to int get()
Moreover, there is one more bug with ideone is that, if you remove constexpr
then still declaring an array is allowed!! I think that's a C99 feature.
Template classes and functions can make use of another kind of template parameter known as a non-type parameter. A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument.
The primary difference between const and constexpr variables is that the initialization of a const variable can be deferred until run time. A constexpr variable must be initialized at compile time.
The constexpr specifier declares that it is possible to evaluate the value of the function or variable at compile time. Such variables and functions can then be used where only compile time constant expressions are allowed (provided that appropriate function arguments are given).
The variable declaration is not marked constexpr . The function parameter isn't constexpr . The function itself isn't marked constexpr , and it's not an immediate function. But arbitrarily we can use the value in a constexpr context.
GCC 4.5 (at least the version used at Ideone) does not entirely support constexpr
, including your valid usage; it waters down to a const
. GCC 4.6 and up correctly supports it.
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