I've got Foo.h:
#include <array>
class Bar {
public:
Bar(std::string name) : name(name) {}
std::string name;
};
class Foo {
public:
enum {ARRAY_SIZE=10};
Foo();
void printElement(int idx);
std::array<Bar,ARRAY_SIZE> myArray;
};
Foo.cc:
#include "Foo.h"
#include <iostream>
Foo::Foo(): myArray({Bar("9"),Bar("8"),Bar("7"),Bar("6"),Bar("5"),
Bar("4"),Bar("3"),Bar("2"),Bar("1"),Bar("0")}) {}
void Foo::printElement(int idx) {
if (idx < ARRAY_SIZE) {
std::cout << "Value is " << myArray[idx].name << std::endl;
} else {
std::cout << "Index out of bounds" << std::endl;
}
}
int main() {
Foo foo;
foo.printElement(1);
}
The problem is that the
{Bar("9"),Bar("8"),Bar("7"),Bar("6"),Bar("5"),Bar("4"),Bar("3"),Bar("2"),Bar("1"),Bar("0")}
is too literal, I need to be able to use an expression which expands to the right size based on the value of ARRAY_SIZE (which could live in an external header file).
Note that in this example I must initialize myArray in the initializer list, otherwise I get this:
(...)/gcc/6.3.0/include/c++/6.3.0/array:90:12: error: no matching function for call to 'Bar::Bar()'
What's the best way to do it?
I'm using g++ 6.3.0 by the way.
ARRAY_SIZEalways fixed? Why not have it as a template parameter?