any是任意对象。配合使用STL容器点,可向此容器添加任意类型的对象。
#include <iostream> #include <string> #include <utility> #include <vector> #include "boost/any.hpp" using namespace std; class A{ public: void some_function(){ cout << "A::some_function()" << endl; } }; class B{ public: void some_function(){ cout << "B::some_function()" << endl; } }; class C{ public: void some_function(){ cout << "C::some_function()" << endl; } }; void print_any(boost::any& a){ if(A* pA = boost::any_cast<A>(&a)) { pA->some_function(); } else if(B* pB = boost::any_cast<B>(&a)) { pB->some_function(); } else if(C* pC = boost::any_cast<C>(&a)) { pC->some_function(); } } int main(){ cout << "Example of using any" << endl; vector<boost::any> store_anything; store_anything.push_back(A()); store_anything.push_back(B()); store_anything.push_back(C()); store_anything.push_back(string("This is great!")); store_anything.push_back(3); store_anything.push_back(make_pair(true, 7.92)); void print_any(boost::any& a); for_each(store_anything.begin(), store_anything.end(), print_any); cin.get(); }