Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[clang-tidy] Check request: use std::tie to implement lexicographical comparison #121367

Open
denzor200 opened this issue Dec 31, 2024 · 0 comments
Labels
check-request Request for a new check in clang-tidy clang-tidy

Comments

@denzor200
Copy link

Assume the structure:

struct A {
    int n;
    std::string s;
    float w;
    float v;
    float d() const noexcept { return w / v; }
};

And this struct has user defined operators with field-by-field manual comparison:

bool operator<(const A& lhs, const A& rhs) noexcept
{
    if (lhs.n != rhs.n) {
        return lhs.n < rhs.n;
    } else if (lhs.s != rhs.s) {
        return lhs.s < rhs.s;
    }
    return lhs.d() < rhs.d();
}

bool operator>(const A& lhs, const A& rhs) noexcept
{
    if (lhs.n != rhs.n) {
        return lhs.n > rhs.n;
    } else if (lhs.s != rhs.s) {
        return lhs.s > rhs.s;
    }
    return lhs.d() > rhs.d();
}

bool operator<=(const A& lhs, const A& rhs) noexcept
{
    return !(lhs > rhs);
}

bool operator>=(const B& lhs, const A& rhs) noexcept
{
    return !(lhs < rhs);
}

We need a check that will suggest to reimplement that operator in a better way using std::tie:

bool operator<(const A& lhs, const A& rhs) noexcept
{
    const auto lhs_d = lhs.d();
    const auto rhs_d = rhs.d();
    return std::tie(lhs.n, lhs.s, lhs_d) < std::tie(rhs.n, rhs.s, rhs_d);
}

bool operator>(const A& lhs, const A& rhs) noexcept
{
    const auto lhs_d = lhs.d();
    const auto rhs_d = rhs.d();
    return std::tie(lhs.n, lhs.s, lhs_d) > std::tie(rhs.n, rhs.s, rhs_d);
}

bool operator<=(const A& lhs, const A& rhs) noexcept
{
    return !(lhs > rhs); // remains unchanged
}

bool operator>=(const B& lhs, const A& rhs) noexcept
{
    return !(lhs < rhs); // remains unchanged
}
@EugeneZelenko EugeneZelenko added the check-request Request for a new check in clang-tidy label Dec 31, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
check-request Request for a new check in clang-tidy clang-tidy
Projects
None yet
Development

No branches or pull requests

2 participants