考虑以下代码:
struct A {
};
struct B {
A a;
bool operator == (const B& other) const = default;
};
clang 给出了一个很好的警告:
warning: explicitly defaulted equality comparison operator is implicitly deleted [-Wdefaulted-function-deleted] bool operator == (const B& other) const = default;
但我想知道为什么这个代码甚至被标准接受。
我假设如果有人在他的非模板结构/类中默认了 operator ==
,他的意图是从不删除 operator ==
。
但这是具有一百万个极端情况的 C++,因此可能有充分的理由。 也许不是特例模板?
但是 clang 足够聪明,不会警告这段代码...
struct A {
};
template<typename T>
struct TS{
T t;
bool operator == (const TS& other) const = default;
};
int main() {
TS<int> ti;
}
...所以理论上标准可以做同样的事情。
最佳答案
在模板中,如果它可以存在,您可能需要 ==
,否则不存在。
相同的技术用于复制/移动/分配特殊成员函数; =default;
也可以删除成员函数。
关于c++ - 为什么 C++20 允许默认比较即使被删除也能编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66051501/