pepero
pepero

Reputation: 7513

function object argument deduction with c++17 CTAD

I have a lot types to use compare functors, and I would like to see if there is way to simplify it without passing the argument. Here is a dummy code example:

struct Base{};

template<typename T> struct Compare {
  bool operator()(const T& a, const T& b) {
    return true;
  }
}; 

int main()
{
    Base b1, b2;
    Compare(b1, b2);
    return 0;
}

Unfortunately, this does not work https://godbolt.org/z/q56c3coaT. But then I wonder how c++17 std::less could work, or there is any way to do it?

Upvotes: 1

Views: 182

Answers (1)

康桓瑋
康桓瑋

Reputation: 42736

Your Compare does not have to be a template class, just convert its operator() into a template function, and create a constexpr object for comparison usage.

struct Compare {
  template<typename T> 
  constexpr bool operator()(const T& a, const T& b) const {
    return true;
  }
}; 
constexpr inline Compare cmp;

Then you can invoke like this:

Base b1, b2;
cmp(b1, b2);

But then I wonder how c++17 std::less could work

C++14 adds the default template parameter void to std::less, and changes the operator() of the partial specialization std::less<void> to template function. Due to the existence of default argument, you can choose not to specify template parameters, but in such case the operator() of std::less<void> will be used.

Upvotes: 2

Related Questions