简体   繁体   English

std :: decay和std :: remove_reference之间的区别

[英]Difference between std::decay and std::remove_reference

When template metaprogramming in C++, I often run into something like the following: 使用C ++进行模板元编程时,我经常遇到以下情况:

template <typename T>
S<T> make_wrapper(T&& t) { return S<T>(std::forward<T>(t)); }

I know I should use something like std::decay in the return type, but why wouldn't std::remove_reference work as well? 我知道我应该在返回类型中使用类似std::decay东西,但是为什么std::remove_reference也不能std::remove_reference工作? What's the difference here? 这有什么区别? What about std::remove_cvref ? 那么std::remove_cvref呢?

Consider for example 考虑一下

#include <type_traits>

int main()
{
    static_assert(std::is_same_v<
        std::decay_t<const int&>, 
        std::remove_reference_t<const int&>
    >); // int != const int
}

std::decay will remove any cv-qualifer, remove_reference won't. std::decay会删除任何cv- remove_referenceremove_reference不会。 It will just strip the "reference" part of the type. 它将只去除类型的“引用”部分。

From the reference : 参考

Applies lvalue-to-rvalue, array-to-pointer, and function-to-pointer implicit conversions to the type T, removes cv-qualifiers, and defines the resulting type as the member typedef type. 将左值到右值,数组到指针和函数到指针的隐式转换应用于类型T,删除cv限定符,并将结果类型定义为成员typedef类型。

Therefore std::decay will perform way more type conversions than std::remove_reference . 因此,与std::remove_reference相比, std::remove_reference std::decay将执行更多的类型转换。

There are also further type modifiers for more nuanced applications that will only perform selected parts of the set of possible transformations decay does, like remove_cv , remove_volatile or, in C++20, remove_cvref . 对于更细微的应用程序,还有其他类型修饰符,它们仅执行decay可能的变换集中的选定部分,例如remove_cvremove_volatile或在C ++ 20中为remove_cvref

Removing reference would leave const and volatile . 删除引用将留下constvolatile If that is what you want, then it will suffice. 如果那是您想要的,那么就足够了。

Removing cvref does most of what decay does, but doesn't convert function types and array types to pointers. 删除cvref可以完成衰减的大部分操作,但是不会将函数类型和数组类型转换为指针。

decay converts a type in a way that you could reasonably store a copy of it in an array or in a struct , or return it from or pass it to a function. 衰减以某种方式转换类型,您可以合理地将其副本存储在数组或struct ,或者将其从函数返回或传递给函数。

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

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