24

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
}

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

Eric
  • 95,302
  • 53
  • 242
  • 374
  • I add `T_cast i{1};` I get `invalid initialization of non-const reference of type 'T_cast' {aka 'int (&)(int)'} from an rvalue of type ''`, so for whatever reason `T_cast` is a `int (&)(int)` rather than a `int (&&)(int)`. – Kevin Oct 05 '19 at 21:59

1 Answers1

21

This is hard-coded in the definition of static_cast:

[expr.static.cast] (emphasis mine)

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

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • [this question](https://stackoverflow.com/q/25146508/102441) addresses in more detail _"rvalue[s] of a function type [not] appear[ing] "in the wild""_ – Eric Oct 06 '19 at 10:25