#include "boost/variant.hpp" #include #include "PerfTimer.h" using namespace std; class my_visitor : public boost::static_visitor { public: int operator()(int i) const { return i; } int operator()(const std::string & str) const { return static_cast( str.length() ); } }; struct Base { int i; std::string s; virtual int len() = 0; }; struct Derived1 : public Base { virtual int len() { return i; } }; struct Derived2 : public Base { virtual int len() { return static_cast(s.length() ); } }; int main() { boost::variant< int, std::string > u("hello world"); int sum = 0; int N = 1000000; Derived2 der; der.i = 10; der.s = "hello world"; Base* b = &der; PerfTimer t; t.start(); for( int i=0; i < N; ++i ) sum += boost::apply_visitor( my_visitor(), u ); t.stop(); std::cout << sum<len(); t.stop(); std::cout << sum<