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<,所以如果我可以避免在每个类中单独定义它,那就太好了。