Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiler warning in static conditional

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?

like image 857
Drahakar Avatar asked Nov 17 '11 03:11

Drahakar


1 Answers

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());
  }
};
like image 98
Kerrek SB Avatar answered Sep 22 '22 02:09

Kerrek SB