问题
I have a class (let's name it TheClass) that is quite often used in the following situation: several instances are constructed from constants and passed as several arguments to some other constructor. Unfortunately I have to use quite cumbersome syntax for the initialization:
Otherclass{ TheClass{1, 'a', 2},
TheClass{1, 'b', 4},
TheClass{3, 'h', 2},
TheClass{1, 't', 8} }
Is there a way to make it possible to initialize the class as if it was POD? I.e. I want to be able to write
Otherclass{ {1, 'a', 2},
{1, 'b', 4},
{3, 'h', 2},
{1, 't', 8} }
Edit: I've posted another question with the correct definition of the problem I'm facing. Please see Is it possible to pass data as initializer_list to std::array of structures?
回答1:
This should do what you want. Alternatively you can typedef TheClass t; or define a macro like this: #define _(x) TheClass x and #undef it afterwards.
#include <initializer_list>
class TheClass {
public:
TheClass(int x, char y, int z) { }
};
class OtherClass {
public:
OtherClass(std::initializer_list<TheClass> t) { }
};
int main (int argc, char **argv) {
OtherClass s { {1,'a',2}, {1, 'b', 4}, {3, 'h', 2}, {1, 't', 8}};
return 0;
}
来源:https://stackoverflow.com/questions/8838636/is-it-possible-to-implement-a-class-in-such-a-way-that-it-would-be-possible-to-v