为何非指针版std::any_cast不返回引用?关于其签名与返回逻辑的疑问
std::any_cast Design Questions Let's tackle your two questions about std::any_cast's design choices—they get at some key semantic differences between the different overloads of this function.
Question 1: Why doesn't the non-pointer version of std::any_cast return a reference?
The non-pointer (value-returning) overload of std::any_cast is designed for extracting a copy (or moved value) of the object stored in the std::any, not for accessing the internal object directly. Here's why returning a reference would be problematic:
- Avoids dangling references: If you called
std::any_caston a temporarystd::anyobject (likestd::any_cast<int>(std::any(42))), returning a reference would give you a dangling reference immediately after the temporary is destroyed. By returning a copy, this risk is eliminated entirely. - Clearer semantics: The pointer/ref overloads exist explicitly for when you want to interact with the internal object (modify it, hold a reference to it long-term). The value overload's job is to safely retrieve the value as a standalone object, separating "get a copy" from "access the original" into distinct, obvious operations.
Question 2: Why does template<class T> T any_cast(any& operand) return T instead of T&?
This overload is specifically meant for value extraction with optional type conversion, not for referencing the internal stored object. Let's break down the documentation's note that it returns static_cast<T>(*std::any_cast<U>(&operand)) (where U is the type actually stored in the std::any):
- Supports type conversion: Unlike the reference-returning overload (which requires
Tto exactly match the stored typeU), this version lets you convert the stored value to a different typeTas long asUcan be converted toT. For example:
If this overload returnedstd::any my_any = 42; // stores an int double converted_val = std::any_cast<double>(my_any); // converts int to doubleT&, this conversion wouldn't be possible—there's nodoubleobject inside thestd::anyto reference. Instead, it creates a newTvalue by converting the internalUvalue, then returns that. - Separates use cases: If you do want a reference to the internal object, you should use the reference-returning overload:
std::any_cast<int&>(my_any). That overload enforces exact type matching and gives you direct access to the stored value.
内容的提问来源于stack exchange,提问作者einpoklum

