在 C++20 中有一些关于重写比较运算符的新规则,我试图了解它们是如何工作的。我遇到了以下程序:
struct B {};
struct A
{
bool operator==(B const&); // #1
};
bool operator==(B const&, A const&); // #2
int main()
{
B{} == A{}; // C++17: calls #2
// C++20: calls #1
}
Run Code Online (Sandbox Code Playgroud)
这实际上破坏了现有的代码。我对此感到有些惊讶;#2实际上对我来说仍然看起来更好:p
那么这些新规则如何改变现有代码的含义呢?
令我惊讶的是,我遇到了另一个障碍,例如C++20 行为用相等运算符破坏了现有代码?.
考虑一个简单的不区分大小写的键类型,用于例如std::setor std::map:
// Represents case insensitive keys
struct CiKey : std::string {
using std::string::string;
using std::string::operator=;
bool operator<(CiKey const& other) const {
return boost::ilexicographical_compare(*this, other);
}
};
Run Code Online (Sandbox Code Playgroud)
简单的测试:
using KeySet = std::set<CiKey>;
using Mapping = std::pair<CiKey, int>; // Same with std::tuple
using Mappings = std::set<Mapping>;
int main()
{
KeySet keys { "one", "two", "ONE", "three" };
Mappings mappings {
{ "one", 1 }, { "two", 2 }, { "ONE", 1 }, { "three", …Run Code Online (Sandbox Code Playgroud) 我有一个方法需要相同枚举类型的多个变量。为了让编译器检测我是否传递了错误的参数,我正在使用BOOST_STRONG_TYPEDEF. 但是,当我创建实例并在 IF 语句中进行比较时,出现段错误。
Boost版本是1.74
enum class Testable
{
UNDEFINED,
A,
B
};
BOOST_STRONG_TYPEDEF(Testable, SomeType)
int main()
{
SomeType abc{Testable::UNDEFINED};
std::cout << "START" << std::endl;
if(abc == Testable::UNDEFINED) // Seg faults here
{
volatile int j = 0;
}
std::cout << "FINISH" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
GDB 回溯表明这是堆栈溢出/递归调用:
#1 0x00007ffff74c5d9d in boost::operators_impl::operator== (y=@0x7fffffcc9e44:
#2 0x00007ffff74c5d9d in boost::operators_impl::operator== (y=@0x7fffffcc9e44:
#3 0x00007ffff74c5d9d in boost::operators_impl::operator== (y=@0x7fffffcc9e44:
#4 0x00007ffff74c5d9d in boost::operators_impl::operator== (y=@0x7fffffcc9e44:
#5 0x00007ffff74c5d9d in boost::operators_impl::operator== (y=@0x7fffffcc9e44:
#6 0x00007ffff74c5d9d in boost::operators_impl::operator== (y=@0x7fffffcc9e44:
Run Code Online (Sandbox Code Playgroud)
没有太多的文档 …