c++ - std::decay 和 std::remove_reference 之间的区别

标签 c++ c++11 templates c++20

在用C++做模板元编程的时候,经常遇到类似下面的情况:

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

我知道我应该在返回类型中使用类似 std::decay 的东西,但为什么 std::remove_reference 不能正常工作?这里有什么区别? std::remove_cvref 怎么样?

最佳答案

举个例子

#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 将删除任何 cv-qualifer,remove_reference 不会。它只会去除类型的“引用”部分。

来自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.

因此 std::decay 将执行比 std::remove_reference 更多的类型转换。

还有更多类型修饰符用于更细微的应用程序,这些应用程序将只执行 decay 所做的一组可能转换的选定部分,如 remove_cvremove_volatile 或者,在 C++20 中,remove_cvref

关于c++ - std::decay 和 std::remove_reference 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47871671/

相关文章:

c++ - 如何在函数模板中声明模板特化?

c++ - 如何在同一台计算机上同时安装多个版本的 llvm libc++(ubuntu)?

c++11 聚合初始化之前的值初始化

c++ - 删除 std::list 的内容

c++ - librdf raptor 处理对象中的整数值

c++ - 是否可以使模板特化等于另一种类型

c++ - 每当调用函数时将值存储在数组中

c++ - 我应该更喜欢 mixin 还是函数模板来为一组不相关的类型添加行为?

c++ - 遍历 function_traits 参数

c++ - 具有副作用的类模板静态成员的初始化