Why is my template operator == not used?

I defined operator==as follows:

template <class State>
bool operator==(const std::shared_ptr<const State> &lhs,
                const std::shared_ptr<const State> &rhs) {
    return *lhs == *rhs;
}

This statement does not receive an instance (in gdbI cannot set a breakpoint in the return statement - the line does not exist).

However, this statement must be used std::find, called on this line:

return std::find(v.begin(), v.end(), el) != v.end();

I checked the type vin the above line in gdb:

(gdb) whatis v
type = const std::vector<std::shared_ptr<Domains::IncWorst const>> &
(gdb) whatis el
type = const std::shared_ptr<Domains::IncWorst const> &

Doesn't that match my pattern operator==with Statebeing IncWorst?

I implemented the toy example as follows, and the example works, so I cannot understand why there is no real code.

template<class V, typename T>
bool in(const V &v, const T &el) {
    return std::find(v.begin(), v.end(), el) != v.end();
}

struct MyState {
    MyState(int xx) : x(xx) {}
    bool operator==(const MyState &rhs) const {
        return x == rhs.x;
    }
    int x;
};

template <class State>
bool operator==(const std::shared_ptr<const State> &lhs,
                const std::shared_ptr<const State> &rhs) {
    return *lhs == *rhs;
}

int main() {
    std::vector<std::shared_ptr<const MyState>> v{
        std::make_shared<const MyState>(5)};
    auto p = std::make_shared<const MyState>(5);
    std::cout << in(v, p) << std::endl; // outputs 1
    return 0;
}
+4
source share
1 answer

operator== .

ADL, std ( , [ namespace.std]/1) Domains ( [basic.lookup.argdep]/2).

, - , (, ), , operator==, [temp.point]/8 [basic.def.odr]/6.

std::shared_ptr , , , - :

struct MyState {
    // ...
};
template bool operator==<MyState>(
    const std::shared_ptr<MyState const>&,
    const std::shared_ptr<MyState const>&);

, - MyState , , , .

+3

Source: https://habr.com/ru/post/1649417/


All Articles