C++ vectors sort ascending/descending How can I eliminate repetition from this code?

std::vector&lt;std::wstring&gt; vec;
bool                      descending;
if (descending)
{
    std::sort(vec.begin(),
              vec.end(),
              std::greater&lt;std::wstring&gt;());
}
else 
{
    std::sort(vec.begin(),
              vec.end(),
              std::less&lt;std::wstring&gt;());
}


I tried 

std::sort(vec.begin(),
          vec.end(),
          descending 
             ? std::greater&lt;std::wstring&gt;()
             : std::less&lt;std::wstring&gt;());


but it fails because greater and less do not evaluate to the same type.

Another question: is it possible to automatically retrieve the required type, std::wstring, from the object vec?
There are a few ways of going about this. One is creating an aggregate type that can forward to the call to the correct comparator. 

template &lt;typename T&gt;
struct comp
{
private:
    bool desc;
    std::greater&lt;T&gt; great;
    std::less&lt;T&gt; less;

public:
    explicit comp(bool descending = false)
      : desc(descending)
    { }

    bool operator()(const T&amp; f, const T&amp; g) const
    {
        return (desc) ? great(f, g) : less(f, g);
    }
};


The downside of this is that a comp object will be at least sizeof(greater + less + bool). This may or may not be a problem. Your call to sort would then look something like:

typedef std::wstring str_t;
bool descending = true;
std::sort(vec.begin(), vec.end(), comp&lt;str_t&gt;(descending));


If the decision is always known at compile time, you can play some template tricks:

template &lt;typename T, bool desc&gt;
struct comp;

template &lt;typename T&gt;
struct comp&lt;T, true&gt;
{
private:
    std::greater&lt;T&gt; great;

public:
    bool operator()(const T&amp; f, const T&amp; g) const
    {
        return great(f, g);
    }
};

template &lt;typename T&gt;
struct comp&lt;T, false&gt;
{
private:
    std::less&lt;T&gt; less;

public:
    bool operator()(const T&amp; f, const T&amp; g) const
    {
        return less(f, g);
    }
};


This requires descending to be const or constexpr:

constexpr bool descending = false;
std::sort(v.begin(), v.end(), comp&lt;str_t, descending&gt;());


This might be a one step forward, two step back kind of solution. It's quite a bit of code to avoid an if/else - you'll need to decide if this is worth it at all.

Edit: As @LokiAstari pointed out, you can simplify the above with inheritance:

template &lt;typename T&gt; 
struct comp&lt;T, true&gt;
  :  std::greater&lt;T&gt;
{ }

template &lt;typename T&gt; 
struct comp&lt;T, false&gt;
  : std::less&lt;T&gt; 
{ }