片段
struct A {
int a;
};
bool operator==(const A& lhs, const A& rhs) { return lhs.a == rhs.a; }
template <typename T>
bool operator==(const A& lhs, const T& rhs) {
return lhs.a == rhs;
}
template <typename T>
bool operator==(const T& rhs, const A& lhs) {
return lhs.a == rhs;
}
struct B : public A {
};
int main() {
A a1, a2;
B b1, b2;
auto c1 = a1 == a2;
auto c2 = static_cast<A>(b1) == static_cast<A>(b2);
auto c3 = b1 == b2;
}
b1 == b2是否可以在沒有 的情況下進行最后一次比較static_cast?是否可以在不重新定義顯式比較運算子的情況下重用的類外比較運算子?AB
Godbolt示例
編輯:我忘了提到這A對我來說是不可變的。我無權訪問它及其比較運算子。
uj5u.com熱心網友回復:
是否可以在沒有 static_cast 的情況下使最后一個比較 b1 == b2 作業?
是的,您可以使用SFINAE,如下所示:
bool operator==(const A& lhs, const A& rhs) { return lhs.a == rhs.a; }
template <typename T>
typename std::enable_if_t<!std::is_same_v<T, B>, bool > operator==(const A& lhs, const T& rhs) {
return lhs.a == rhs;
}
template <typename T>
typename std::enable_if_t<!std::is_same_v<T, B>,bool> operator==(const T& rhs, const A& lhs) {
return lhs.a == rhs;
}
int main() {
A a1, a2;
B b1, b2;
auto c1 = a1 == a2;
auto c2 = b1 == b2; //works now
auto c3 = b1 == b2;
}
作業演示。
或與 C 20 一起使用requires
bool operator==(const A& lhs, const A& rhs) { return lhs.a == rhs.a; }
template <typename T> bool operator==(const A& lhs, const T& rhs)
requires (!std::is_same_v<T, B>)
{
return lhs.a == rhs;
}
template <typename T>bool operator==(const T& rhs, const A& lhs)
requires (!std::is_same_v<T, B>)
{
return lhs.a == rhs;
}
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/528250.html
上一篇:通過方法設定類屬性的值
