gpt4 book ai didi

c++ - std::declval 是如何工作的?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:58:05 28 4
gpt4 key购买 nike

有人可以解释一下 std::declval 是如何工作的吗?我在 gcc headers/type_traits(第 2248-2262 行)中找到了这个实现,它是(清理了一下以提高可读性):

template<typename _Tp>
struct __declval_protector
{
static const bool __stop = false;
static typename add_rvalue_reference<_Tp>::type __delegate();
};

template<typename _Tp>
typename add_rvalue_reference<_Tp>::type
declval ()
{
static_assert(__declval_protector<_Tp>::__stop, "declval() must not be used!");
return __declval_protector<_Tp>::__delegate();
}

我不明白 return __declval_protector<_Tp>::__delegate() 部分,它是否为 T 类型的右值引用调用默认初始化程序?我也不明白为什么 static_assert每次打电话都不叫declval , 自 __stop总是错误的(它如何区分未评估的上下文和已评估的上下文?)。

编辑:据我现在的理解,所有这些东西等同于:

template<typenam _Tp>
struct __declval_protector
{
const bool __stop = false;
};

template<typename _Tp>
typename add_rvalue_reference<_Tp>::type
mydeclval ()
{
static_assert(__declval_protector<_Tp>::__stop, "declval() must not be used!");
}

但是编译器当然会提示我们没有返回任何东西。

最佳答案

I don't understand why the static_assert is not called every time I call declval, since __stop is always false

你的前提是错误的。每次调用 declval 时,确实会调用静态断言 。诀窍是您绝不能调用declval。它只能在未评估的上下文中使用。这就是静态断言存在的原因。

关于c++ - std::declval 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37843196/

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