Since C++17 std::any
is introduced. One can now write code like this
#include <iostream>
#include <any>
#include <string>
int main () {
const double d = 1.2;
std::any var = d;
const std::string str = "Hello World";
var = str;
}
A double is assigned to the variable var
and than a std::string
was assigned to it.
Why has std::any
been introduced?
I think this is violating the least astonishment rule
, because I find it hard to think of a situation, where this can be used to express more clearly, what I like to express.
Can somebody give me a good example, when std::any
is beneficial.
When to Use
void*
as an extremely unsafe pattern with some limited use cases,std::any
adds type-safety, and that’s why it has some real use cases.Some possibilities:
(ref)