将特定类型的所有变量初始化为C ++中的特定默认值 [英] Initialize all the variables of a specific type to a specific default value in C++
问题描述
在我的代码中,我有 int
s, bool
s,指针
s等,我也用 typedef
定义了一些类型,我该如何管理默认值初始化,例如它在带有约束的对象中发生的情况?
In my code i have int
s, bool
s, pointer
s and so on, i also have some type defined by me with typedef
, how can i manage the default value initialization like it happens in the objects with the contrunctor?
我想确定
T var;
如果不加修改,则始终等于我的默认值,而我喜欢这样做而无需解析每一行代码手动更改默认值,而无需使用预处理程序宏。
if untouched, is always equal to my default value and i like to do this without parsing each line of code anche changing the default value manually and without using a preprocessor macro.
这可能吗?
是否可以定义新的 typedef
?
推荐答案
在C ++ 11中,您可以编写 T var {};
将值初始化为默认值。
In C++11, you could write T var{};
to get value initialization to the default value.
在C ++ 03中,您可以编写一个非POD包装器,其默认构造函数将由 T var;
:
In C++03, you could write a non-POD wrapper, whose default constructor will get called by T var;
:
template<class T>
struct default_initializer{
default_initializer() : value() {}
default_initializer(T const& v) : value(v) {}
T value;
};
// somewhere in code
default_initializer<T> var; // calls default ctor and initializes 'value'
// to its default value
此将允许您安全地默认初始化基本类型,POD和聚合类型,这些类型通常由 T var;
声明未初始化。
This will allow you to safely default initialize even primitive , POD and aggregate types, which are normally left uninitialized by the T var;
declaration.
这篇关于将特定类型的所有变量初始化为C ++中的特定默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!