3CxEZiVlQ
3CxEZiVlQ

Reputation: 38834

Retrieve the type of an unnamed struct for using it in a member function

How to get the type of an unnamed struct for using it in a member function?

struct {
  using P = int;  // What should be instead of int?

  bool operator<(const P& r) {
    return false;
  }
} obj1, obj2;

int main() {
  obj1 < obj2;
  return 0;
}

Upvotes: 2

Views: 68

Answers (1)

songyuanyao
songyuanyao

Reputation: 172994

You can make the operator< a template, and constrain the type with std::enable_if. E.g.

template <typename P>
auto operator<(const P& r) -> std::enable_if_t<std::is_same_v<P, std::remove_reference_t<decltype(*this)>>, bool> {
  return false;
}

Upvotes: 1

Related Questions