0

I have seen this question, but the solution provided there doesn't solve the issue.

static int num_instances; 
std::vector<SomeClass::FunctionWithinTheClass> *mem[num_instances];

SomeClass::FunctionWithinTheClass *mem[num_instances]; //Even this raises an error

the value num_instances is obtained by reading a configuration file.

The error I get is : array bound is not an integer constant before ‘]’ token

This is strange because the value num_instances is fixed at compile time.

tandem
  • 2,040
  • 4
  • 25
  • 52

3 Answers3

1

Perhaps it is fixed at compile time but “integer constant” is a technical term and a static int variable does not meet these requirements.

Use a static const int instead. This works:

static const int num_instances = 5;

However, you mention that num_instances is read from a configuration file… this does not sound remotely like a constant to me. In this case, you must use a std::vector or other dynamically sized array instead.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
1

the value num_instances is obtained by reading a configuration file

and

... the config file is read at runtime

That means num_instances is a variable whose value is determined at run time.

This is strange because the value num_instances is fixed at compile time

No it isn't, you're contradicting yourself.

If it's loaded from config at run time, it wasn't known at compile time. If it was known at compile time, you wouldn't be loading it from config at run time.


If you cannot fix num_instances at compile time, an array is the wrong thing to use. Just change it to

// like an array whose size can be set at runtime ...
std::vector<std::vector<SomeClass::FunctionWithinTheClass>> mem;

void configure() {
    size_t num_instances = loadNumInstancesFromConfig();
    mem.resize(num_instances);
}
Useless
  • 64,155
  • 6
  • 88
  • 132
  • Why is it `std::vector – tandem Dec 06 '17 at 15:38
  • What did I say it was trying to achieve? What would make sense? How does it read when you match the `<...>` brackets around the template parameter lists? – Useless Dec 06 '17 at 15:40
  • I reread that and understood it better, which leads me to a new error: `request for member resize in ..., which is of pointer type (maybe you meant to use ->` – tandem Dec 06 '17 at 15:42
  • Did you declare `mem` as a pointer still? It doesn't need to be, which is why I didn't declare it as one. – Useless Dec 06 '17 at 15:45
0

Even if the value is fixed, it's not a compile time constant, if you want dynamically sized container might I suggest you use stl containers?

Immac
  • 466
  • 1
  • 5
  • 16