私はこれを次のように行います。これはクリーンで安全だと思います。
any_extension.hpp:
namespace cpputil
{
struct AnyWriter
{
/// Register a type with the AnyWriter.
/// @pre T must have an ostream << operator available somewhere
template<class T> static bool registerType()
{
return registeredTypes().emplace(std::type_index(typeid(T)),
std::bind(&AnyWriter::write<T>,
std::placeholders::_1,
std::placeholders::_2)).second;
}
/// Write any registred object to a stream
/// @pre Underlying type must have been registered with a call to AnyWriter::registerType<T>
/// @param os is reference to a std::ostream
/// @param anyObject is a reference to a boost::any
static void writeAny(std::ostream& os, const boost::any& anyObject);
private:
// A function object that converts an any to a type and streams it to an ostream
using WriteFunction = std::function<void (std::ostream&, const boost::any&)>;
// a map of typeinfo to WriteFunction
using RegisteredTypes = std::unordered_map<std::type_index, WriteFunction >;
// retrieve the WriteFunction map in a safe way
static RegisteredTypes& registeredTypes();
// Convert an any to a type, and write it to a stream
template<class T> static void write(std::ostream& os, const boost::any& anyObject) {
try {
const T& typedObject = boost::any_cast<const T&>(anyObject);
os << typedObject;
}
catch(boost::bad_any_cast& e) {
os << "<exception in conversion: " << e.what() << ">";
}
}
};
}
namespace std {
ostream& operator<<(ostream& os, const ::boost::any& anyObject);
}
any_extension.cpp:
#include "any_extension.h"
#include <string>
namespace cpputil {
namespace AnyWriterRegistration {
const bool stringRegistered = AnyWriter::registerType<std::string>();
const bool intRegistered = AnyWriter::registerType<int>();
const bool doubleRegistered = AnyWriter::registerType<double>();
}
AnyWriter::RegisteredTypes& AnyWriter::registeredTypes()
{
static RegisteredTypes _registrationMap;
return _registrationMap;
}
void AnyWriter::writeAny(std::ostream &os, const boost::any &anyObject)
{
auto registered = registeredTypes();
auto iFind = registered.find(anyObject.type());
if(iFind == registered.end()) {
os << "<unregistered type: " << anyObject.type().name() << ">";
}
else {
iFind->second(os, anyObject);
}
}
}
namespace std {
ostream& operator<<(ostream& os, const ::boost::any& anyObject)
{
if(anyObject.empty()) {
os << "<empty>";
}
else {
cpputil::AnyWriter::writeAny(os, anyObject);
}
return os;
}
}
サポートしたい型については、その型に対して AnyWriter::register() が呼び出され、その型に対して operator<< が存在することを確認してください。
例えば:
any_test.cpp:
struct chicken {};
std::operator<<(std::ostream& os, const chicken& aChicken) {
os << "cluck!";
return os;
}
namespace {
const bool chickenRegistered = AnyWriter::register<Chicken>();
}
void chickenTest() {
boost::any animal = chicken();
std::cout << animal << std::endl;
}
出力: カチャッ!