我想出了一个定义一个通用比较运算符的想法,它可以用于任何类型,以获得它的乐趣.
#include <cstring>
#include <iostream>
class A
{
public:
A(int id) : id(id) {}
private:
int id;
};
template <class T>
inline bool operator==(const T& a, const T& b)
{
return memcmp(&a, &b, sizeof(a)) == 0; // implementation is unimportant (can fail because of padding)
}
int main()
{
std::cout << (A(10) == A(10)) << std::endl; // 1
std::cout << (A(10) == A(15)) << std::endl; // 0
}
Run Code Online (Sandbox Code Playgroud)
我认为这可以用来解决c ++中缺少默认比较运算符的问题.
这是一个糟糕的主意吗?我想知道在某些情况下这样做是否会破坏任何东西?
constexpr但是,虚函数不能,当函数通过继承隐式虚拟时,我试过的编译器不会抱怨它.
这是一个示例代码:
class A
{
virtual void doSomething() {}
};
class B : public A
{
constexpr void doSomething() override {} // implicitly virtual constexpr
// but no compilation error
};
class C : public A
{
virtual constexpr void doSomething() override {} // explicitly virtual constexpr
// compilation error
};
Run Code Online (Sandbox Code Playgroud)
我gcc 7.2.0和它一起尝试过.clang 5.0.0
这些编译器在这方面不符合标准,还是constexpr允许隐式虚函数?