I have class Phenotype with the following constructor:
Phenotype(uint8 init[NUM_ITEMS]);
I can create a Phenotype like this:
uint8 data[] = {0,0,0,0,0};
Phenotype p(data);
But I get an error when I try to create one like this:
Phenotype p = {0,0,0,0,0};
Output:
$ make
g++ -Wall -g main.cpp -std=c++0x
main.cpp: In function ‘int main(int, char**)’:
main.cpp:109: error: no matching function for call to ‘Phenotype::Phenotype(<brace-enclosed initializer list>)’
main.cpp:37: note: candidates are: Phenotype::Phenotype(uint8*)
The error seems to indicate that there is a way to define a constructor which takes a brace-enclosed initializer list. Does anyone know how this might be done?
In C++0x it seems you can create a constructor for this. I have no experience with it myself, but it looks like it's called initializer list-constructor.
It can only be done for aggregates (arrays and certain classes. Contrary to popular belief, this works for many nonpods too). Writing a constructor that takes them is not possible.
Since you tagged it as "C++0x", then this is possible though. The magic words is "initializer-list constructor". This goes like
However, such initialization will default construct the array and then use the assignment operator. If you aim for speed and safety (you get compile time errors for too many initializers!), you can also use an ordinary constructor with a variadic template.
This can be more generic than needed though (often an initializer_list completely suffices, especially for plain integers). It benefits from perfect forwarding, so that an rvalue argument can be move constructed into an array element
It's a hard choice!
Edit Correction, the last one works too, as we didn't make the constructor
explicit
, so it can use the copy constructor ofPhenotype
, constructing a temporaryPhenotype
object and copy it over top3
. But that's not what we really would want the calls to be :)You need to use the std::initializer_list template type. Example: