Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile-time array constants

I seem to be missing something rather fundamental. I'm trying to use const array members at compile-time.

const int list[3] = { 2, 5, 7 };
const int a = list[2]; // this doesn't error?

template<int N1, int N2>
struct tmax {
  enum { value = ((N1 > N2) ? N1 : N2) };
};

const int b = tmax<2,4>::value;
const int c = tmax<list[0],list[1]>::value; // error is here

int main()
{
  return 0;
}

Errors:

prog.cpp:10:24: error: 'list' cannot appear in a constant-expression
prog.cpp:10:30: error: an array reference cannot appear in a constant-expression

Here is the relevent IDEOne link

So why doesn't this work? What am I missing? What should I do differently?

like image 730
std''OrgnlDave Avatar asked Jun 09 '12 23:06

std''OrgnlDave


1 Answers

Just because an object is const doesn't mean it's a compile time constant expression.

main.cpp:10:20: error: non-type template argument is not a constant expression
const int c = tmax<list[0],list[1]>::value; // error is here
                   ^~~~~~~
main.cpp:10:20: note: read of non-constexpr variable 'list' is not allowed in a constant expression
main.cpp:1:11: note: declared here
const int list[3] = { 2, 5, 7 };
          ^

This is the reason for constexpr:

constexpr int list[3] = { 2, 5, 7 };

template<int N1, int N2>
struct tmax {
    enum { value = ((N1 > N2) ? N1 : N2) };
};

const int b = tmax<2,4>::value;
const int c = tmax<list[0],list[1]>::value; // works fine now

As for why this works:

const int a = list[2]; // this doesn't error?

initializing a const variable doesn't require a constant expression:

int foo(int n) {
    const int a = n; // initializing const var with a non-compile time constant
like image 182
bames53 Avatar answered Oct 06 '22 17:10

bames53