我经常在代码中遇到POD结构,这些结构是手动零初始化的,memset如下所示:
struct foo;
memset(&foo, 0, sizeof(foo));
Run Code Online (Sandbox Code Playgroud)
我检查了C++ 11标准,它说:"一个对象,其初始化器是一组空的括号,即(),应该进行值初始化." 接下来是: "对T类型的[pod结构]进行值初始化意味着...对象被零初始化."
所以......这是否意味着您可以随时安全地将上述代码压缩为以下代码:
struct foo{};
Run Code Online (Sandbox Code Playgroud)
并且有一个保证初始化的结构,就好像你已经调用了一样memset(&foo, 0, ...)?
如果是这样,那么一般来说,你可以使用空的初始化器安全地初始化任何东西,如下所示:
SomeUnknownType foo{}; // will 'foo' be completely "set" to known values?
Run Code Online (Sandbox Code Playgroud)
我知道在C++ 03中(在统一初始化语法之前)并不总是可行的,但现在C++ 11中是否可以用于任何类型?
在模板参数包中确定常用数字类型的最佳方法是:
可变参数模板(best_common_numeric_type)可以像这样使用:
template<typename... NumericTypes>
auto some_numeric_func(const NumericTypes&...)
-> typename best_common_numeric_type<NumericTypes...>::type;
Run Code Online (Sandbox Code Playgroud)
并具有以下实例:
[1] best_common_numeric_type<long, unsigned long, float, double, int>::type = double
[2] best_common_numeric_type<unsigned int, unsigned long>::type = unsigned long
[3] best_common_numeric_type<signed int, signed long>::type = signed long
[4] best_common_numeric_type<signed int, unsigned int>::type = signed long
[5] best_common_numeric_type<signed int, unsigned long>::type = int128_t (maybe)
Run Code Online (Sandbox Code Playgroud)
因此,例如,在情况[4]中,::type必须是signed long,因为signed int无法保持unsigned int没有溢出的风险,并且反过来unsigned int不能保持signed int没有下溢的风险.
这同样适用于[5],除了现在a signed long …
c++ templates template-meta-programming variadic-templates c++11