是否可以防止省略聚合初始化成员? [英] Is it possible to prevent omission of aggregate initialization members?
问题描述
我有一个结构,其中有许多相同类型的成员,像这样
I have a struct with many members of the same type, like this
struct VariablePointers {
VariablePtr active;
VariablePtr wasactive;
VariablePtr filename;
};
问题是,如果我忘记初始化一个结构成员(例如 wasactive
),就像这样:
The problem is that if I forget to initialize one of the struct members (e.g. wasactive
), like this:
VariablePointers{activePtr, filename}
编译器不会抱怨它,但是我将有一个部分初始化的对象.如何防止这种错误?我可以添加一个构造函数,但是它将重复两次变量列表,因此我必须键入所有这三次!
The compiler will not complain about it, but I will have one object that is partially initialized. How can I prevent this kind of error? I could add a constructor, but it would duplicate the list of variable twice, so I have to type all of this thrice!
如果有针对C ++ 11的解决方案,请也添加 C ++ 11 的答案(当前我仅限于该版本).不过,也欢迎使用最新的语言标准!
Please also add C++11 answers, if there's a solution for C++11 (currently I'm restricted to that version). More recent language standards are welcome too, though!
推荐答案
这是一个技巧,如果缺少所需的初始化程序,则会触发链接器错误:
Here is a trick which triggers a linker error if a required initializer is missing:
struct init_required_t {
template <class T>
operator T() const; // Left undefined
} static const init_required;
用法:
struct Foo {
int bar = init_required;
};
int main() {
Foo f;
}
结果:
/tmp/ccxwN7Pn.o: In function `Foo::Foo()':
prog.cc:(.text._ZN3FooC2Ev[_ZN3FooC5Ev]+0x12): undefined reference to `init_required_t::operator int<int>() const'
collect2: error: ld returned 1 exit status
注意事项:
- 在C ++ 14之前,这完全阻止了
Foo
的聚合. - 从技术上讲,这依赖于未定义的行为(违反了ODR),但应在任何理智的平台上都可以使用.
这篇关于是否可以防止省略聚合初始化成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!