I was reading the documentation for std::any_cast
and I find it strange that the API has the cast either return a value to the held object or a pointer to it. Why not return a reference? A copy needs to be made every time the function is called with a non pointer type argument.
I can see that the pointer version of the cast might signal intentions a bit more and might be a bit more clear but why not have the value returned be a reference like this?
template<typename ValueType>
ValueType& any_cast(any* operand);
instead of
template <typename ValueType>
ValueType* any_cast(any* operand);
Further it seems like even if you ask for a reference the cast removes the reference and returns a copy to the stored object see the explanations for the return values for function overloads 1-3 here http://en.cppreference.com/w/cpp/utility/any/any_cast
Anycast is a network addressing and routing method in which incoming requests can be routed to a variety of different locations.
Performance of std::any Also, invoking a std::any_cast to retrieve the value is quite slow compared to std::variant . The Boost equivalent of std::any , boost::any , provides a fast version of std::any_cast called boost::any_cast_unsafe which can be utilized if you know which type is contained.
Here are the things to remember about std::any : std::any is not a template class. std::any uses Small Buffer Optimization, so it will not dynamically allocate memory for simple types like ints, doubles… but for larger types it will use extra new .
You can see a discussion regarding the C++ standard for this here: https://groups.google.com/a/isocpp.org/forum/#!topic/std-proposals/ngSIHzM6kDQ
Note that Boost has defined any_cast
this way for more than a decade, plus it matches static_cast
and friends. So if you want a reference, do this:
any_cast<Foo&>(x)
The same as you'd do for the older _cast
s in C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With