我在重载operator==、使用VC++(2015)和g++ 5.4.0 (-std==c++14)时出现了不同的编译器错误。下面是代码(这只是我实际代码库中一个更复杂情况的摘录):
#include <vector>
template<typename T>
struct A {
struct B {
std::vector<T> _elements;
// Internal cmp op.
bool operator==(const B &other) {
return _elements == other._elements;
}
};
std::vector<B> _entries;
};
// External cmp op.
template<typename T>
inline bool operator==(typename const A<T>::B &l, typename const A<T>::B & r) {
return l._elements == r._elements;
}
int main() {
A<int>::B b0, b1;
b0.operator==(b1); // a
operator==<int>(b0, b1); // b
b0 == b1; // c
std::vector<A<int>::B> v0, v1;
std::equal(v0.begin(), v0.end(), v1.begin()); // d
v0 == v1; // e
return 0;
}我不添加错误消息,因为我有德文版本的VC++和g++错误跨越了许多行。
VC++给出了(e)的一个错误。我不明白为什么,因为vector<>::operator==似乎在内部调用std::equal,并且(d)编译得很好。为什么会失败呢?
g++无法接受我的外部operator==(),因此完全无法编译这段简短的代码。我不知道如何为A::B编写用于这两个编译器的外部operator==()。
我还没试过拍拍呢。
非常感谢。
发布于 2017-02-21 20:35:51
您的程序中有两个错误:
// Internal cmp op.
bool operator==(const B &other) const {
///// <- here
return _elements == other._elements;
}应该是const成员,关键字const不能出现在typename后面。
// External cmp op.
template<typename T>
inline bool operator==(typename A<T>::B const& lhs, typename A<T>::B const& rhs)
///// <- here -> ////
{
return lhs._elements == rhs._elements;
}请注意,const的位置在C++中通常是相当宽松的,例如您可以同时编写const typename A<T>::B & lhs和typename A<T>::B const& lhs,但是您选择的形式typename const A<T>::B & lhs是不允许的。
还请注意,您想要编写一个成员operator==或一个非会员operator==,但永远不要两者都写。在您的例子中,由于T is not deducible In typename A<T>::B,您必须编写丑陋的operator==<int>(b0, b1)来选择非成员。
我将移除非会员模板operator==,并向类模板A<T>添加一个非会员模板。
bool operator==(const A &other) const {
return _entries == other._entries;
}这样您也可以比较A<int>的对象。请注意,这将调用std::vector的标准库std::vector,而后者又将为B调用您的operator==。
https://stackoverflow.com/questions/42377251
复制相似问题