I recently came across the std::any
class, introduced in C++17, based on boost::any
. This class can "hold an instance of any type" and auto
automatically deduces the data type of a variable.
So what is the main difference? What are the pros and cons?
std::any
andauto
are completely different constructs.std::any
is a container type that can hold an object of any type:The type of the object held by
std::any
can change during the execution of the program.auto
is a keyword that designates a placeholder type. The type of a variable withauto
is the type of the value used to initialize the variable:This type is determined statically, i.e. at compile time, and can never change during the execution of the program.
These constructs are not interchangeable, and so they have different use cases, and you can't compare the pros and cons of one versus the other meaningfully.