Proposal: make Glib::KeyFile easier to use
- From: Povilas Kanapickas <povilas radix lt>
- To: gtkmm-list gnome org
- Subject: Proposal: make Glib::KeyFile easier to use
- Date: Thu, 26 Dec 2013 01:39:05 +0200
Hello all,
The current interface of Glib::KeyFile::get_* functions is quite
inconvenient as exceptions are the only reliable way to receive error
conditions. Consider the following example:
Glib::KeyFile f;
<...>
int x = f.get_integer("a", "b"); // (1)
There are two possible error conditions that may cause (1) to fail:
* there's no key "b" in group "a"
* the value of the key "b" in group "a" is not an integer
Whereas the former condition can be checked for via KeyFile::has_key, to
check for the latter, one has only the following two options:
* catch the thrown exception
* get the value via get_string and use a separate function to parse it
Both of these approaches are not optimal. I think the situation could be
improved.
My proposal is as follows:
* A new class template Glib::Optional<T> is created. The new class
template would be identical to boost::optional[1].
* A new family of functions for reading a keyfile is created (say, for
example, get_*_opt). The new functions would return Glib::Optional<T>
instead of T. All error conditions would be reported by returning
'empty' optional object. The new functions would not throw any
exceptions on any circumstances.
This would allow much simpler usage of the API. For example:
Glib::KeyFile f;
<...>
auto opt = f.get_integer_opt("a", "b"); // let's say we can use C++11
if (opt) {
// utilize the value in *opt
int r = *opt;
<...>
}
Note, that the conditional is not necessary. Trying to 'dereference' an
empty optional object would throw an exception, so the behavior is
pretty much the same as if using the 'old' get_integer function. Note,
however, that the optional objects have value semantics, even though
access to the stored value is done through overloaded operator* and
operator->.
It is likely that this is not the only case throughout Gtkmm, where a
template similar to boost::optional would simplify the API. The idiom
itself is very well known. It is almost a certainty that the C++
standard will include std::optional in 2017 or thereabouts
(std::optional was going to be included into C++14, but minor problems
with comparison operators caused it to be moved into a separate
specification).
Any opinions? I volunteer to implement the proposal, but before I begin,
I would like to hear what do the maintainers think.
Regards,
Povilas
[1]: http://www.boost.org/doc/libs/1_55_0/libs/optional/doc/html/index.html
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]