I’m writing statistic system. It should make some output with given params. For example:
float getSunActivity() { ... }
int getEarthActivity() { ... }
StatisticSystem::track("sun_activity", boost::any(getSunActivity()));
StatisticSystem::track("earth_activity", boost::any(getEarthActivity()));
class StatisticSystem
{
typedef std::map<string, const boost::any*> stats;
stats mStatsData;
static void track(const string &name, const boost::any ¶m);
void update();
};
StaticSystem::track(const string &name, const boost::any ¶m)
{
mStatsData[name] = ¶m;
}
StaticSystem::update()
{
BOOST_FOREACH(stats::value_type &row, mStatsData)
{
string data = lexical_cast<string>(&row.second);
cout << data << "\n";
// Usage of 'data' value
}
}
Look, each update calling I need in the new value of all passed variables. So I decided to pass their addresses in the memory. But now the data consist of address. How can I receive value from it? Is it possible, if not, what could you advice for this problem?
I suggest not using BOOST_FOREACH in this case as it might be somewhat harder for the reader of the code what’s going on under the hood. You can rewrite the update function using plain iterators:
However, this alone won’t make your code work. There are some other bugs/bad design:
1) Do not use boost::any unless completely necessary – it’s a heavy template class that slows down the compilation and gives no hint what actual types are stored inside. A better approach would be creating classes
EarthActivityandSunActivitythat would both derive from a common classActivityand then useActivity*instead ofboost::any*as the map parameter. In case the returned values are only primitive ones (like thefloatandintin your example), why does Sun returnfloatand Earthint? You should usefloat/doublefor both.2) You are accessing a member of the class
StatisticSysteminside the static method track, this is invalid and will not compile. If you are trying to implement a Singleton pattern, there are a lot of tutorials on how to make it correctly, for instance this one: http://www.yolinux.com/TUTORIALS/C++Singleton.html3) You are missing return types of the functions. If you want the functions to return nothing, specify
voidas their return type: