简体   繁体   English

内置类型的模板参数默认值

[英]Template argument default value for built-in types

Consider this function: 考虑这个功能:

template <typename T>
T foo(const T& var = T()) {
  return var;
}

This call is obviously safe: 这个电话显然是安全的:

foo<std::string>()

Are those? 那些是吗?

foo<int>()
foo<bool>()
...

Yes, they are perfectly fine. 是的,他们完全没问题。 An expression of the form T() creates an object of type T and value-initializes it. T()形式的表达式创建一个T类型的对象并对其进行初始化。 Value-initializing an int or bool is the same as zero-initializing them. 初始化intbool的值与初始化它们相同。 That is, the parameter var will have value 0. 也就是说,参数var值为0。

The expression T() , where T is a simple-type-specifier or typename-specifier for a non-array complete object type [...] creates a prvalue of the specified type, whose value is that produced by value-initializing (8.5) an object of type T 表达式T() ,其中T是非数组完整对象类型的简单类型说明符类型名称说明 [...]创建指定类型的prvalue,其值是由值初始化生成的( 8.5) T类型的对象

Value-initialization is defined as: 值初始化定义为:

To value-initialize an object of type T means: 对值类型T的对象进行值初始化意味着:

  • if T is a (possibly cv-qualified) class type [...] 如果T是(可能是cv限定的)类类型[...]

  • if T is a (possibly cv-qualified) non-union class type [...] 如果T是(可能是cv合格的)非联盟类类型[...]

  • if T is an array type, [...] 如果T是数组类型,[...]

  • otherwise, the object is zero-initialized. 否则,该对象被零初始化。

Zero-initialization is defined as: 零初始化定义为:

To zero-initialize an object or reference of type T means: 零初始化T类型的对象或引用意味着:

  • if T is a scalar type (3.9), the object is set to the value 0 (zero), taken as an integral constant expression, converted to T ; 如果T是标量类型(3.9),则将对象设置为值0 (零),作为整数常量表达式,转换为T ;

  • [...] [...]

The temporary object created by T() is then bound to the const reference, which extends its lifetime. 然后,由T()创建的临时对象绑定到const引用,从而延长其生命周期。

There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression. 有两种情况,临时表在与完整表达结束时不同的地方被摧毁。 [...] The second context is when a reference is bound to a temporary. [...]第二个上下文是指引用绑定到临时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM