samedi 4 mars 2017

C++ Change member function definition based on template parameter value

Is it possible to conditionally compile a statement in a function based on the value of a template parameter? For example:

template<typename T, bool chk>
class subject
{
public:
    // the ideal case    
    void doSomething(T new_val)
    {
        if(chk)
        {
          if(new_val != val)
              //do_something only if new_val is different from val
        }
        else
        {
            //do_something even if new_val and val are equal
        }
    }


    //or if that's not possible, if chk = 0 use this method
    void doSomething(T new_val) 
    {
        //do_something even if new_val and val are equal
    }

    // and if chk = 1 use this method
    void doSomething(T new_val) 
    {
        if(new_val != val)
           //do_something only if new_val is different from val
    }

    T val;
};

the catch is based on the value of chk I don't even want the statement if(new_val!=val) compiled into the function (because then every type T used would have to have a != operator defined).

I guess one drawback to this approach is that foo<int,0> and foo<int,1> are different classes so it wouldn't be possible to define a function that doesn't care if chk is 0 or 1 (say watch(foo<int>)).

The application I'm looking at specifically is an observer and for some types I only want the observer to be notified if the value actually changes and for other types I want the observer to always be notified (and for those types I don't want to have to define a != operator).

Is this possible without having two separate classes?

Aucun commentaire:

Enregistrer un commentaire