Compiler warning in static conditional

I use the template parameter to determine if a specific behavior needs to be done or not. But this code generates a warning on VS2008: Warning 26 warning C4127: conditional expression is constant

Here is an example code:

 template <class param, bool param2=true> class superclass1 { public: int foo() { if(param2) doSomthingMore(); return 1; } }; 

Is there a way to convert the code to remove the warning and get the same functions?

+6
source share
2 answers

This is done through partial specialization. The coarsest version looks like this:

 template <typename, bool> class superclass1; template <class param> class superclass1<param, true> class superclass1 { public: int foo() { doSomthingMore(); return 1; } }; template <class param> class superclass1<param, false> class superclass1 { public: int foo() { return 1; } }; 

A more sophisticated approach is to declare a member template function and only specialize in this. Here's a solution with helper tag classes:

 #include <type_traits> template <bool B> class Foo { struct true_tag {}; struct false_tag {}; void f_impl(true_tag = true_tag()){} // your code here... void f_impl(false_tag = false_tag()){} // ... and here public: void foo() { f(typename std::conditional<B, true_tag, false_tag>::type()); } }; 
+4
source

Or simply attach your secret code with #pragma warning( disable : 4127 ) and #pragma warning( default: 4127 ) so as not to write the same logic twice (although this does not apply to the simple case described in the question).

0
source

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


All Articles