gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:08:47 28 4
gpt4 key购买 nike

在用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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com