std::any
is a vocabulary type. When you need to store, well, some bit of anything, as a value you can use it.
There are a number of "first level" uses of it:
When interacting with scripting languages which themselves have such types, it is a natural fit.
When you have a property tree with highly polymorphic content, and the structure of the tree is decoupled from the producer and consumer of the tree.
When replacing the equivalent of a void*
chunk of data being passed through an intermediate layer who really doesn't care what it is carrying.
It can also be used as a building block in other cases. For example, std::function
could choose to store its value in the std::any
:
template<class R, class...Args>
struct func<R(Args...)> {
mutable std::any state;
R(*f)(std::any& state, Args&&...) = nullptr;
template<class T>
void bind(T&& t) {
state = std::forward<T>(t);
f = [](std::any& state, Args&&...args)->R {
return std::any_cast<T&>(state)(std::forward<Args>(args)...);
};
}
R operator()(Args...args)const {
return f(state, std::forward<Args>(args)...);
}
};
that is a pretty small implementation of (most of) std::function
. Basically I've used any
to type erase copy/move/destroy.
You can using this elsewhere for similar problems (where you are type-erasing some operation and also want to type erase copy/move/destroy), or generalize it.
std::any
to obfuscate code, then sure it violates the least astonishment rule. If you use it as a safervoid*
(see the article T.C. linked to), it's anything but astonishing. – Crackbrainedstd::any
where in the past you would have usedvoid*
. Which is to say, ideally, almost nowhere. – Saunder