For reading INI configuration file boost:property_tree
can be used in the way as follows:
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
int main()
boost::property_tree::ptree pt;
boost::property_tree::ini_parser::read_ini("config.ini", pt);
int N = pt.get<int>("Section.ValueOfN");
However I have a class Class
which has a static const variable N
. The variable is static because there are millions of instances of this class and I do not need each Class
to remember the value of N
while it is constant and the same for each of them.
If variable Class::N
is static const int, then I declare it in Class.hpp and define it in Class.cpp this way:
//Class.hpp
class Class
{
static const int N;
}
//Class.cpp
const int Class::N = 42;
But what if I want to load it from a configuration file? N
is static variable and as such it has to be defined out of any function. On the other side I have to define property_tree
inside of function, but if it is inside of function I can't use it to define static const variable.
If it would be this way:
//Class.hpp
class Class
{
static const int N;
}
//Class.cpp
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
boost::property_tree::ptree pt;
boost::property_tree::ini_parser::read_ini("config.ini", pt);
const int Class::N = pt.get<int>("Section.ValuOfN");
I would get an error on the line with read:ini
:
error: expected constructor, destructor, or type conversion before ‘(’ token
I can solve it this way:
//Class.hpp
class Class
{
static const int N;
}
//Class.cpp
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
namespace {
int getFromINI(const std::string& section, const std::string& value)
{
boost::property_tree::ptree pt;
boost::property_tree::ini_parser::read_ini("config.ini", pt);
return pt.get<int>(section + "." + value);
}
}
// Define constant static variables
const int Class::N = getFromINI("Section","ValueOfN");
As you can see, this is not an ideal solution. I have to make an property_tree
for each static const variable I want to define and the tree is used only once. And of course I have to improve getFromINI
function to be able to read other types than int.
Any suggestions?