代码之家  ›  专栏  ›  技术社区  ›  Eric

为什么'decltype(static\u cast<T>(…))`not always`T`?

  •  5
  • Eric  · 技术社区  · 5 年前

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

    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 ?

    1 回复  |  直到 5 年前
        1
  •  21
  •   StoryTeller - Unslander Monica    5 年前

    这是硬编码的定义 static_cast

    [表达式静态转换] (重点是我的)

    1 表达式的结果 static_­cast<T>(v) 就是结果 转换表达式 v 键入 T . 如果 是左值 引用类型或对函数类型的rvalue引用,结果是 左值 ;如果 T 是对对象类型的rvalue引用,结果是 xvalue;否则,结果是prvalue。这个 static_­cast

    decltype 考虑其操作数的值类别,并为左值表达式生成左值引用。