I use a template parameter to determine if a certain behavior must be done or not. But this code generate a warning on VS2008 : Warning    26  warning C4127: conditional expression is constant
Here an exemple of the code :
template <class param, bool param2=true>
class superclass1
{
public:
  int foo()
  {
     if(param2)
        doSomthingMore();
     return 1;
   }
};
Is there a way to tranform the code to remove the warning and get the same features?
This is done via partial specialization. The crudest 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 might declare a member template function and only specialize that. Here's a solution with auxiliary 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());
  }
};
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With