Is it possible to implement a class in such a way that it would be possible to value initialize it as if it was POD

我的未来我决定 提交于 2019-12-13 18:44:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!