How to declare an array with const size inside of class?

I wanted to add that the template argument is needed because its a "special case" but if that doesn't work what would be the next best way to solve this problem. I want to be able to declare the const size of the array outside the class far removed from it actually. I'm actually going off this page

http://c2.com/cgi/wiki?TooFewTemplateParameterLists

Heres the code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

template <int F>
class C
{
 public:

    static int constant;
    int array[constant];
};
int main()
{
   template <const int F>
   const int C<F>::constant = 0;
   std::cout << C<2>::constant << std::endl; // 0

   return 0;
}


1
2
3
4
const_template_parameters_int_main.cpp|9|error: array bound is not an integer constant|
const_template_parameters_int_main.cpp||In function 'int main()':|
const_template_parameters_int_main.cpp|13|error: expected primary-expression before 'template'|
const_template_parameters_int_main.cpp|13|error: expected ';' before 'template'|

Last edited on
<scratch>

(misread question...)

Andy

PS But according to ANSI C++, if you're using your member variable 'constant' to specify the array size, then it has (a) to be const (as well as static) and (b) assigned a value greater than zero. (You could set it to F?)

And lines 13 and 14 don't make sense. Is this an attempt at specialization?

Well, I'm not sure what you're trying to do, but you can do this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

template <int F>
class C
{
 public:

    static int constant;
    int array[F];
};

template <int F>
int C<F>::constant = F;

int main()
{
   C<2>::constant = 0;
   std::cout << C<2>::constant << std::endl; // 0

   return 0;
}



Last edited on
If it creates an array of size 2 then yes, that would be correct.
Topic archived. No new replies allowed.