add_lvalue_reference_t< T>与和T& [英] Difference between add_lvalue_reference_t<T> and T&
问题描述
假设您有一个模板参数 T
。
Suppose you have a template argument T
.
$ b有什么区别
-
add_cv_t< T>
和const volatile T
-
add_const_t< T>
和const T
-
add_volatile_t< T>
和volatile T
-
add_lvalue_reference_t< T>
和T&
-
add_rvalue_reference_t< ; T>
和T&&
-
add_pointer_t< T>
和T *
?
add_cv_t<T>
andconst volatile T
add_const_t<T>
andconst T
add_volatile_t<T>
andvolatile T
add_lvalue_reference_t<T>
andT&
add_rvalue_reference_t<T>
andT&&
add_pointer_t<T>
andT*
?
为什么要使用例如, add_rvalue_reference_t< T>
而不是 T&
。
Why should I use add_rvalue_reference_t<T>
instead of T&&
for example. Are there any rules when to choose which?
推荐答案
add_cv_t< T>
和const volatile T
add_const_t< ; T>
和const T
add_volatile_t< T>
和易失性T
add_cv_t<T>
andconst volatile T
add_const_t<T>
andconst T
add_volatile_t<T>
andvolatile T
无差异;例如, add_const< T> :: type
的定义就是 T const
。
No difference; the definition of add_const<T>::type
is just T const
, for example.
add_lvalue_reference_t< T>
和T&
add_rvalue_reference_t< T>
和T&&
add_lvalue_reference_t<T>
andT&
add_rvalue_reference_t<T>
andT&&
T&
和<当 T
为 cv 时,code> T&
格式错误无效,但这些模板格式正确,只是返回了原始类型。
T&
and T&&
are ill-formed when T
is cv void
, but these templates are well-formed, just giving the original type back.
add_pointer_t< T>
和T *
?
add_pointer_t<T>
andT*
?
add_pointer_t< T>
等效于 std :: remove_reference< T> ; :: type *
。也就是说,如果 T
是引用类型,它将给出指向该引用类型的指针。另一方面, T *
格式错误,因为您无法找到引用的指针。
add_pointer_t<T>
is equivalent to std::remove_reference<T>::type*
. That is, if T
is a reference type, it gives a pointer to the referenced type. On the other hand, T*
will be ill-formed since you cannot have a pointer to a reference.
您应该使用哪个?
- 通常,别名模板可用于防止扣除
T
。当然,这意味着如果要扣除,就应该避免使用它们。 - 别名模板可用作将类型转换作为参数的模板的模板模板参数。 / li>
- 别名行为与
T *
之类的替代方式不同的别名模板在通用代码中很有用,因为它们做正确的事。例如,如果从T&&
类型的参数推导出T
,则当参数是左值时,T *
会做错事情,因为它试图声明一个指向左值引用的指针。但是std :: add_pointer_t< T>
将提供指向参数实际类型的指针。
- In general, the alias templates can be used to prevent deduction of
T
. Of course, that means that if you want deduction, you should avoid them. - The alias templates can be used as template template arguments to a template that takes a type transformation as a parameter.
- The alias templates that differ in behaviour from alternatives like
T*
are useful in generic code since they "do the right thing". For example, ifT
is deduced from an argument of typeT&&
, thenT*
does the wrong thing when the argument is an lvalue, since it tries to declare a pointer to an lvalue reference. Butstd::add_pointer_t<T>
will give a pointer to the actual type of the argument.
这篇关于add_lvalue_reference_t< T>与和T&的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!