c++ - Specializing single method in a big template class -


in c++ if want partially specialize single method in template class have specialize whole class (as stated example in template specialization of single method templated class multiple template parameters)

this becomes tiresome in bigger template classes multiple template parameters, when each of them influences single function. n parameters need specialize class 2^n times!

however, c++11 think there might more elegant solution, not sure how approach it. perhaps somehow enable_if? ideas?

in addition inheritance-based solution proposed torsten, use std::enable_if , default function template parameters enable/disable specializations of function.

for example:

template<typename t> struct comparer {     template<typename u = t ,     typename std::enable_if<std::is_floating_point<u>::value>::type* = nullptr>     bool operator()( u lhs , u rhs )     {         return /* floating-point precision aware comparison */;     }      template<typename u = t ,     typename std::enable_if<!std::is_floating_point<u>::value>::type* = nullptr>     bool operator()( u lhs , u rhs )     {         return lhs == rhs;     }  }; 

we take advantage of sfinae disable/enable different "specializations" of function depending on template parameter. because sfinae can depend on function parameters, not class parameters, need optional template parameter function, takes parameter of class.

i prefer solution on inheritance based because:

  • it requires less typing. less typing leads less errors.
  • all specializations written inside class. way write specializations holds of specializations inside original class , , make specializations function overloads, instead of tricky template based code.

but compilers have not implemented optional function template parameters (like msvc in vs2012) solution not work, , should use inheritance-based solution.

edit: ride on non-implemented-default-function-template-parameters wrapping template function other function delegates work:

template<typename t> struct foo { private:     template<typename u>     void f()     {         ...     }  public:     void g()     {         f<t>();     } }; 

of course compiler can inline g() throwing away wrapping call, there no performance hit on alternative.


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -