-
Notifications
You must be signed in to change notification settings - Fork 2
Using custom classes with scl::config_file
While the standard data types of C++ can be useful, it is often helpful to use your own classes and OOP to make a more intuitive framework. This guide will briefly explain how to make your custom classes work with SCL's config_file class like a standard data type.
The config_file class uses std::stringstream to convert values to and from the strings used in the internal buffer. Since stringstream derives from the generic ostream and istream classes, we can make custom classes work with SCL much the same way as making a custom class work with cin and cout.
Example Custom Class that would work with config_file:
//a class which allows incrementing two seperate values
class dual_counter {
public:
int a = 0;
int b = 0;
//constructor
dual_counter() {
//initialize things here...
}
dual_counter(int init_a, int init_b) {
a = init_a;
b = init_b;
}
//for writing the class to the config file
friend ostream& operator<<(ostream& os, const dual_counter& ct) {
os << ct.a << " " << ct.b;
return os;
}
//for reading the class from a config file
friend istream& operator>>(istream& is, dual_counter& ct) {
is >> ct.a >> ct.b;
return is;
}
};The important bits in this snippet are the overloaded operators, friend ostream& operator<< and friend istream& operator>>. These allow the class to properly interact with streams, including iostreams and stringstreams. The above class could then be interacted with by SCL like so:
using namespace scl;
//write
config_file write_file("example.config", config_file::WRITE);
dual_counter counter(3, 5);
//do things to the counter here...
write_file.put("my_counter", counter);
write_file.write_changes();
write_file.close();
//read
config_file read_file("example.config", config_file::READ);
read_file.load()
dual_counter other_counter = read_file.get<dual_counter>("my_counter");
read_file.close();Please note that if your class does not have a default constructor (that is, one that takes no parameters) then you will have to specify the value of def when calling get.
Further reading: