Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-line difference in c++ template

Tags:

c++

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?

like image 872
AcmeZexe Avatar asked Dec 30 '16 19:12

AcmeZexe


1 Answers

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;
}
like image 166
Dietmar Kühl Avatar answered Oct 20 '22 19:10

Dietmar Kühl