Single line difference in C ++ template

I was provided with several classes, and only one of them uses the .open method, and the rest use .load

Is there a smarter way to achieve something like the (simplified) code below? Or should I change the definitions of the above classes?

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; } 

It 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 that

 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 enough?

+6
source share
1 answer

Assuming the actual code is not as simple as indicated, it might be prudent to customize the function template with the actual operation. For instance:

 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; } 
+3
source

Source: https://habr.com/ru/post/1013652/


All Articles