(C++) boost::any

August 17, 2019 · View on GitHub

boost::any is a Boost container for type-safe storage of any data type.

 

 

 

 

 

Project and source code

 

Operating system: Ubuntu 10.04 LTS Lucid Lynx

IDE: Qt Creator 2.0.0

Project type: Qt4 Console Application

Compiler: G++ 4.4.1

Libraries used:

 

 

 

 

 

 

main.cpp

 


#include <algorithm> #include <iostream> #include <string> #include <vector> #include <boost/any.hpp> int main() {   std::vector<boost::any> v;   v.push_back(boost::any(123));   v.push_back(boost::any(123.456));   v.push_back(boost::any(std::string("123")));   std::random_shuffle(v.begin(),v.end());   const std::size_t sz = v.size();   for (std::size_t i = 0; i!=sz; ++i)   {     if (v[i].type() == typeid(int))     {       std::cout << "int found at index '" << i         << "': " << boost::any_cast<int>(v[i]) << '\n';     }     else if (v[i].type() == typeid(double))     {       std::cout << "double found at index '" << i         << "': " << boost::any_cast<double>(v[i]) << '\n';     }     else if (v[i].type() == typeid(std::string))     {       std::cout << "std::string found at index '" << i         << "': " << boost::any_cast<std::string>(v[i]) << '\n';     }   } }

 

Screen output:

 


int found at index '0': 123 std::string found at index '1': 123 double found at index '2': 123.456