Boost.Any做這項工作的一類。這應該基本上做作者顯示:
#include <iostream>
#include <string>
#include <map>
#include <typeindex>
#include <boost/any.hpp>
class heterogenous_map :
std::map<std::type_index, boost::any>
{
public:
template <typename T>
void add(T&& value)
{
emplace(typeid(typename std::remove_reference<T>::type), std::forward<T>(value));
}
template <typename T>
T & get() { return *boost::any_cast<T>(&at(typeid(T))); }
template <typename T>
T const& get() const { return *boost::any_cast<T>(&at(typeid(T))); }
};
int main()
{
heterogenous_map map;
map.add(6584);
map.add<std::string>("Hi!");
std::cout << "My favourite integer: " << map.get<int>() << '\n';
std::cout << "My favourite string : " << map.get<std::string>() << std::endl;
}
Demo。
那麼問題是什麼?你可能想看看[Boost.Any](http://www.boost.org/doc/libs/release/doc/html/any.html)來存儲不同的值。 – 2014-10-27 14:03:13
對不起,我希望得到如何實現上述接口的建議。 謝謝,我會看看Boost :: Any。 – daddycool 2014-10-27 14:42:17