Skip to content

Instantly share code, notes, and snippets.

@yomichi
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yomichi/3ff97a47132be9b899a7 to your computer and use it in GitHub Desktop.
Save yomichi/3ff97a47132be9b899a7 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <boost/any.hpp>
#include <complex>
struct Any{
boost::any any_;
template <class T>
Any(T const& x):any_(x){}
template <class T>
Any& operator=(T const& x){ any_ = x; return *this;}
template <class T>
operator T() const{ return boost::any_cast<T>(any_);}
};
#define Print(name) (std::cout << #name << " = " << name << std::endl)
int main()
{
Any a = 42; // int
int i = a;
Print(i);
a = 3.14; // double
double d = a;
Print(d);
// i = a; // FAIL to cast (double to int), and throw runtime error
a = std::complex<double>(0.0,1.0); // complex
std::complex<double> z = a;
Print(z);
// d = a; // FAIL to cast (complex to double), and throw runtime error
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment