Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

c++ - Why C++20 allows defaulted comparison to compile even when it is deleted?

Consider the following code:

struct A {
};
struct B {
    A a;
    bool operator == (const B& other) const = default;
};

clang gives a nice warning :

warning: explicitly defaulted equality comparison operator is implicitly deleted [-Wdefaulted-function-deleted] bool operator == (const B& other) const = default;

But I wonder why is this code even accepted by the standard. I would assume that if somebody defaults the operator == in his nontemplate struct/class his intention is never to get deleted operator ==.

But this is C++ with a million corner cases so there might a good reason. Maybe not to special case templates?

But clang is smart enough to not warn on this code...

struct A {
};

template<typename T>
struct TS{
    T t;
    bool operator == (const TS& other) const = default;
};
int main() {
    TS<int> ti;
}

... so in theory standard could do the same.

question from:https://stackoverflow.com/questions/66051501/why-c20-allows-defaulted-comparison-to-compile-even-when-it-is-deleted

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In a template, you may want == if it can exist, and otherwise not.

The same technique is used for copy/move/assign special member functions; =default; can delete the member function as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...