0

Id like to say that there's a ton of C++ Overloading questions already on SO, but after an hour of looking at them and other posts on forums and newsgroups, I'm still stumped.

Background

I've created a namespace, call it A, where a bunch of classes have the same way of implementing the < operator. In order to avoid code duplication, I wrote this:

namespace A{
     template<typename T>
     bool operator< (const T&, const T&);
}

In a header file called operator_forwards.h along with a few other declarations. I then made it a friend to the correct classes by adding a line like this:

//example.h
#include "operator_forwards.h"
namespace A{
    template<typename T>
    class Example{
        public:
        friend bool operator< <>(const Example<T>&, const Example T&);
        private:
        T start;
    };
} 

Finally, I put the definition in a file called operators.h like this:

namespace A{
    template<typename T>
    bool operator<(const T& lhs, const T& rhs){
        using std::operator<;
        return lhs.start<rhs.start;
    }
}

And included everything in one header file:

//A.h
#include "example.h"
#include "operators.h"

The Problem

The problem is when I call operator< like this:

Example<vector<int>::iterator> ex1(**foo**);
Example<vector<int>::iterator> ex2(**bar**);
ex1<ex2;

它调用 A::operator< 很好,但是它递归地调用自己来做ex1.start<ex2.start而不是查找更专业的 operator< 用于 vector::iterator。导致错误 C2039: start is not a member of vector::iterator。

有人对确保 A::operator< 为 ex1.start 调用正确的 operator< 有任何建议吗?

注意:大约有 20 个类使用 A::operator<,所以如果我可以避免在每个类中单独定义它,那就太好了。

4

1 回答 1

2

我谦虚的建议:不要那样做。

除了实施A::operator<. 任何地方的任何代码都A可能被这个声称支持operator<任何东西的意外模板迷惑,但实际上只能在具有start成员的类型上执行它。

就您而言,您在friend任何地方的每个相关类中都放置了一个声明。在这些类中简单地实现它几乎不需要任何代码。如果这冒犯了您的代码重复敏感性,请考虑使用共享基类:

template <typename T>
class IterWrapper {
public:
    IterWrapper() {}
    explicit IterWrapper(T it) : start(it) {}

    bool operator< (const IterWrapper<T>& rhs) { return start < rhs.start; }
protected:
    T start;
};
于 2012-08-25T17:49:29.423 回答