是否可能实现一个类,以这样一种方式,它是可能的值初始化它就像是POD [英] 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
问题描述
我有一个类(让我们把它命名为 TheClass
)在下面的情况下经常使用:几个实例从常量构造,作为几个参数传递给其他构造函数。不幸的是,我必须使用相当繁琐的语法来初始化:
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} }
有没有办法使初始化类像POD一样?也就是说我想能够写
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} }
编辑:我发布了另一个问题,我正面临的问题的正确定义。请参阅是否可以将数据作为initializer_list传递到std ::结构数组?
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?
推荐答案
这应该做你想要的。你也可以 typedef TheClass t;
或者定义一个这样的宏: #define _(x)TheClass x
code> #undef 之后。
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;
}
这篇关于是否可能实现一个类,以这样一种方式,它是可能的值初始化它就像是POD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!