3

私は現在、大規模なコード プロジェクトに取り組んでおり、この機会に名前空間について学び、使用したいと考えていました。私が定義したすべてのクラスは、単一の名前空間 Test 内にあります。

ここで Thing と呼ばれる私のクラスの 1 つには、一意の ID があります。いくつかのモノへの参照の std::vector を保持できる必要があるため、std::reference_wrappers を使用しています。プログラムのポイントで、特定の std::reference_wrappers をベクターから削除する必要があるため、std::find を使用します。

#include <algorithm>
#include <functional>
#include <vector>

namespace Test {

class Thing {
private:
    const int id;

public:
    Thing(int id);
    const int ID() const;
};

}

Test::Thing::Thing(int id) : id(id) { }

const int Test::Thing::ID() const {
    return id;
}

inline bool operator==(const Test::Thing& lhs, const Test::Thing& rhs) {
    return lhs.ID() == rhs.ID();
}
inline bool operator!=(const Test::Thing& lhs, const Test::Thing& rhs) {
    return !(lhs == rhs);
}

int main() {
    Test::Thing t1(5);
    Test::Thing t2(7);

    auto ref1 = std::ref(t1);
    auto ref2 = std::ref(t2);

    std::vector<std::reference_wrapper<Test::Thing>> v;
    v.push_back(ref1);
    v.push_back(ref2);

    auto pos = std::find(v.begin(), v.end(), ref2);
}

これをコンパイルしようとすると、エラーが発生します。

error: no match for ‘operator==’ (operand types are ‘std::reference_wrapper<Test::Thing>’ and ‘const std::reference_wrapper<Test::Thing>’)

ただし、名前空間を削除すると、コードは正しくコンパイルされます。

#include <functional>
#include <vector>
#include <algorithm>

class Thing {
private:
    const int id;

public:
    Thing(int id);
    const int ID() const;
};

Thing::Thing(int id) : id(id) { }

const int Thing::ID() const {
    return id;
}

inline bool operator==(const Thing& lhs, const Thing& rhs) {
    return lhs.ID() == rhs.ID();
}
inline bool operator!=(const Thing& lhs, const Thing& rhs) {
    return !(lhs == rhs);
}

int main() {
    Thing t1(5);
    Thing t2(7);

    auto ref1 = std::ref(t1);
    auto ref2 = std::ref(t2);

    std::vector<std::reference_wrapper<Thing>> v;
    v.push_back(ref1);
    v.push_back(ref2);

    auto pos = std::find(v.begin(), v.end(), ref2);
}
4

1 に答える 1