Le Laboureur Le Laboureur - 3 months ago 6
C++ Question

Can we have a template not on type but on operation

I'm new to C++.
I currently have 2 classes with the EXACT same code except at some point one class uses the '<' operator and the others uses '>'.

Is there any way to merged those classes and declare a template on '' operator?

Answer

To begin with, if your problem is really limited to < and >, then you can make a base class taking a boolean stating whether to use one or the other.

class base
{
protected:
    base(bool use_less) : m_use_less{less}

    some_return_type my_fn(some_args args)
    {
         ...
         const bool cmp = m_use_less? a < b: a > b;
         ...
    }

private:
    const bool m_use_less;
}

If lines such like

const bool cmp = m_use_less? a < b: a > b;

repeat too many times in your code, you can consider making an inline method that does this.


If you want, though, you can generalize the comparison much further, as many standard library algorithms (for example, std::sort), which does exactly this.

Typically, standard-library algorithms solve it as follows (the following assumes you're operating on integers):

#include <functional>

// Pass the comparison as a template argument
template<class Compare=std::less<int>>
class my_class
{
 private:
    // A comparison object
    Compare m_cmp;

 public:
    some_return_type my_fn(some_args args)
    {
        ...
        const bool is_less = m_cmp(lhs, rhs);    
        ...
    }

};

By default, this class uses < (via std::less). If you want to use >, simply instantiate with std::greater.