c++ - Using an element of a constexpr array vs a const array to instantiate a template -


while answering a question, ran issue couldn't explain.

it seems there large enough difference between

constexpr size_t intarray[2] = {1, 2}; 

and

const size_t intarray[2] = {1, 2}; 

that elements of first can used instantiate template not elements of second.

sample program demonstrates difference.

#include <cstddef>  template <size_t n> struct foo {};  // works fine void test1() {    constexpr size_t intarray[2] = {1, 2};    const size_t = intarray[0];    foo<i> f;    (void)f; // remove unused f warning. }  // not work void test2() {    const size_t intarray[2] = {1, 2};    const size_t = intarray[0];    foo<i> f;    (void)f; // remove unused f warning. }  int main() {    return 0; } 

i following compiler error using g++ 4.9.2.

g++ -std=c++11 -wall    socc.cc   -o socc  socc.cc: in function ‘void test2()’: socc.cc:17:8: error: value of ‘i’ not usable in constant expression     foo<i> f;         ^ socc.cc:16:17: note: ‘i’ not initialized constant expression     const size_t = intarray[0];                  ^ socc.cc:17:9: error: value of ‘i’ not usable in constant expression     foo<i> f;          ^ socc.cc:16:17: note: ‘i’ not initialized constant expression     const size_t = intarray[0];                  ^ socc.cc:17:9: note: in template argument type ‘long unsigned int’     foo<i> f;          ^ socc.cc:17:12: error: invalid type in declaration before ‘;’ token     foo<i> f; 

my question why constexpr array work not const array?

constexpr ensures value compile time value whereas const forbids modify value.

whereas mark single const variable if compile time value or not, c-array, require remember information each index.

even if can do

const int 2 = 2; constexpr int two_bis = two; 

the following not permit

const size_t intarray[2] = {1, bar()}; // non constexpr bar()  constexpr size_t = intarray[0]; // might know compile time value constexpr size_t b = intarray[1]; // 1 not 

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -