Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it valid to use constexpr function as template argument?

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.

like image 736
iammilind Avatar asked Jun 15 '11 07:06

iammilind


People also ask

Can we pass Nontype parameters to templates?

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.

Should I use constexpr or const?

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.

What is constexpr used for?

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).

Can a function parameter be constexpr?

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.


1 Answers

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.

like image 134
Luc Danton Avatar answered Oct 04 '22 14:10

Luc Danton