How to avoid re-writing the same patterns?

Consider, for example, the following example, where two template classes depend on each other:

template <class T1, class T2, typename = typename std::enable_if<std::is_blah<T1>::value>::type, typename = typename std::enable_if<std::is_blah<T2>::value>::type> class someClass { // ... template <class U1, class U2, typename = typename std::enable_if<is_blah<U1>::value>::type, typename = typename std::enable_if<std::is_blah<U2>::value>::type> void fun1(U1 arg1, U2 arg2) { // ... } template <class U1, class U2, typename = typename std::enable_if<std::is_blah<U1>::value>::type, typename = typename std::enable_if<std::is_blah<U2>::value>::type> void fun2(U1 arg1, U2 arg2) { // ... } template <class U1, class U2, typename = typename std::enable_if<std::is_blah<U1>::value>::type, typename = typename std::enable_if<std::is_blah<U2>::value>::type> void fun3(U1 arg1, U2 arg2) { // ... } // ... }; 

Right In situations like the ones described above, I have to write the same pattern over and over again. Needless to say, this is ugly, makes the code unreadable, tedious and unpleasant, includes many copies, etc. Etc.

There just has to be a reasonable decision.

One, of course, should #define this template. I don’t think this is a big problem, since of course I can #undef it as soon as I am done with all the declarations and definitions. But perhaps this is wrong; I am just green and I have seen people blaming any #defines.

Any other solutions? Or is this macro solution the best available?

+4
source share
1 answer

The only solution I see is to define some user-defined type functions and aliases that achieve two goals:

  • make your code more concise and (possibly) readable;
  • make mantenance easier (i.e., as you pointed out in your comment , if you need to make changes, you will only have to do one place)

For example, you can change

 template<typename T1, typename T2, typename = typename std::enable_if<std::is_pod<T1>::value>::type, typename = typename std::enable_if<std::is_pod<T2>::value>::type> struct C1{}; 

in

 template<typename T> using Eif_pod = typename std::enable_if<std::is_pod<T>::value>::type; template<class T1, class T2, class = Eif_pod<T1>, class = Eif_pod<T2>> struct C2{}; 
+3
source

All Articles