为什么`decltype(static_cast< T>(...))`并不总是`T`? [英] Why is `decltype(static_cast<T>(...))` not always `T`?

查看:83
本文介绍了为什么`decltype(static_cast< T>(...))`并不总是`T`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下代码,除最后一个断言外,所有消息均通过:

For the following code, all but the last assertion passes:

template<typename T>
constexpr void assert_static_cast_identity() {
    using T_cast = decltype(static_cast<T>(std::declval<T>()));
    static_assert(std::is_same_v<T_cast, T>);
}

int main() {
    assert_static_cast_identity<int>();
    assert_static_cast_identity<int&>();
    assert_static_cast_identity<int&&>();
    // assert_static_cast_identity<int(int)>(); // illegal cast
    assert_static_cast_identity<int (&)(int)>();
    assert_static_cast_identity<int (&&)(int)>(); // static assert fails
}

为什么最后一个断言失败,并且 static_cast< T> 并不总是返回 T ?

Why is this last assertion failing, and static_cast<T> not always returning a T?

推荐答案

这是在 static_cast 的定义中硬编码的:

This is hard-coded in the definition of static_cast:

[expr.static.cast] (强调我的意思)

1 表达式 static_cast< T>(v)是结果将表达式 v 转换为 T 的过程.如果 T 是左值引用类型或函数类型的右值引用,结果是左值;如果 T 是对对象类型的右值引用,则结果为一个xvalue;否则,结果为prvalue. static_cast 操作员不得抛弃常数.

1 The result of the expression static_­cast<T>(v) is the result of converting the expression v to type T. If T is an lvalue reference type or an rvalue reference to function type, the result is an lvalue; if T is an rvalue reference to object type, the result is an xvalue; otherwise, the result is a prvalue. The static_­cast operator shall not cast away constness.

decltype 尊重其操作数的值类别,并为左值表达式生成左值引用.

decltype respects the value category of its operand, and produces an lvalue reference for lvalue expressions.

推理可能是由于函数名称本身始终是左值,因此函数类型的右值不能在野外"出现.因此,强制转换为这种类型可能毫无意义.

The reasoning may be due to function names themselves always being lvalues, and so an rvalue of a function type cannot appear "in the wild". As such, casting to that type probably makes little sense.

这篇关于为什么`decltype(static_cast&lt; T&gt;(...))`并不总是`T`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆