Recursive spaceship operator

217 views Asked by At

I have written this simple code but it does not compile because the comparison is implicit deleted.

struct Tree {
    std::vector<Tree> child;

    friend auto operator<=>(const Tree &a, const Tree &b) = default;
}
int main(){
    Tree t;
    std::cout<<(t<t)<<std::endl;
}

Can anybody explain to me how to fix the problem or at least why it does not work?

Edit: compiled with "g++ -std=gnu++2a main.cpp" Edit2: Here is the error part of the output (it is followed by many, many lines of candidates):

main.cpp: In function 'int main()':
main.cpp:31:25: error: use of deleted function 'constexpr auto operator<=>(const Tree&, const Tree&)'
   31 |     std::cout << (tmp < tmp) << std::endl;
      |                         ^~~
main.cpp:12:17: note: 'constexpr auto operator<=>(const Tree&, const Tree&)' is implicitly deleted because the default definition would be ill-formed:
   12 |     friend auto operator<=>(const Tree &a, const Tree &b) = default;
      |                 ^~~~~~~~
main.cpp:12:17: error: no match for 'operator<=>' (operand types are 'std::vector<Tree>' and 'std::vector<Tree>')

1

There are 1 answers

3
n. m. could be an AI On BEST ANSWER

You cannot usually define a recursive function with a deduced return type. In order to deduce it, you need to already know it, so this is a no go.

Replacing auto with an explicit return type std::weak_ordering fixes the problem.