95 lines
2.4 KiB
C++
95 lines
2.4 KiB
C++
/*
|
|
* File: HeterogeneousMap.h
|
|
* Author: jgaebler
|
|
*
|
|
* Created on February 13, 2014, 9:37 AM
|
|
*/
|
|
#pragma once
|
|
|
|
#ifndef HETEROGENEOUSMAP_H
|
|
#define HETEROGENEOUSMAP_H
|
|
|
|
#include <string>
|
|
#include <map>
|
|
#include "boost/any.hpp"
|
|
#include "common/Exception.h"
|
|
|
|
namespace ubeeme {
|
|
namespace moversight {
|
|
|
|
class HeterogeneousMap {
|
|
public:
|
|
|
|
HeterogeneousMap();
|
|
virtual ~HeterogeneousMap();
|
|
|
|
template<typename T>
|
|
void set(const char * key, const T & t);
|
|
|
|
template<typename T>
|
|
T get(const char * key);
|
|
|
|
private:
|
|
std::map<std::string, boost::any> storage;
|
|
|
|
};
|
|
|
|
/**
|
|
* @brief Sets an element within the map.
|
|
* @see std::map#operator[]
|
|
* @param key The key identify the element to store
|
|
* @param t The element to store
|
|
*/
|
|
template<typename T>
|
|
void
|
|
HeterogeneousMap::set(const char * key, const T & t) {
|
|
|
|
if (!storage[key].empty()) {
|
|
if (storage[key].type() != typeid (T)) {
|
|
std::stringstream buf;
|
|
buf << "bad type, expect " << storage[key].type().name() << " for key: " << key;
|
|
throw ParameterException(buf.str().c_str());
|
|
|
|
}
|
|
storage[key] = t;
|
|
}
|
|
else {
|
|
storage[key] = t;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @brief Returns the element stored under that key. Is no element
|
|
* stored under this key, a new, empty one is created, using the
|
|
* default constructor.
|
|
* @param key The key identifies the element to read.
|
|
* @return The desired element, or an empty instances of the target type,
|
|
* if no element stored under that key.
|
|
*/
|
|
template<typename T>
|
|
T
|
|
HeterogeneousMap::get(const char * key) {
|
|
|
|
if (storage[key].empty()) {
|
|
return T();
|
|
}
|
|
else {
|
|
|
|
if (storage[key].type() == typeid (T)) {
|
|
return boost::any_cast<T>(storage[key]);
|
|
}
|
|
else {
|
|
std::stringstream buf;
|
|
buf << "bad type, expect " << storage[key].type().name() << " for key: " << key;
|
|
throw ParameterException(buf.str().c_str());
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
}
|
|
}
|
|
|
|
#endif /* HETEROGENEOUSMAP_H */
|
|
|