I've been given some classes, and only one use .open method, while the others use .load
Is there any smarter way to achieve something like the (simplified) code below? Or should I edit the aforementioned classes' definitions?
template <class element> bool load (element & el, std::string file) {
bool status;
if (std::is_same <element, some_special_class>::value) {
status = el.open (file);
} else {
status = el.load (file);
}
// lot of code, based on status
return status;
}
This seems a little better
void lotOfCode (bool status) {
if (status) {
// some code
} else {
// more code
}
}
template <class el> bool load (el & e, std::string f) {
bool status = e.load (f);
lotOfCode (status);
return status;
}
bool load (some_special_class & e, std::string f) {
bool status = e.open (f);
lotOfCode (status);
return status;
}
than this
template <class element> bool load (element & el, std::string file) {
if (el.load (file)) {
// some code
return true; // loaded
}
// more code
return false;
}
bool load (some_special_class & el, std::string file) {
if (el.open (file)) {
// some code
return true; // loaded
}
// more code
return false;
}
but is it good enough?
Assuming the actual code isn't as simple as posted, it may be reasonable to customize the function template with an operation which is actually applied. For example:
template <typename T>
bool load_aux(T& t, std::string const& s) { return t.load(s); }
bool load_aux(some_special_case& t, std::string const& s) { return t.open(s); }
template <typename T>
bool load(T& t, std::string const& s) {
if (load_aux(t, s)) {
// some code
return true;
}
// some more code
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With