重载 == 和 !=,但程序只使用前者
Overloading == and !=, but program only use the former
我的代码是这样的
template <typename T>
class FArray
{
/* ... */
inline bool operator == (const FArray& b) const
{
return std::equal(begin(),end(),b.begin());
}
inline bool operator != (const FArray& b) const
{
return !(*this == b);
}
};
然后我有一些单元测试,我正在测试平等和不平等
FArray<double> a, b, c;
/* ... */
ASSERT_TRUE(a == b)
ASSERT_TRUE(a != c)
第二个断言不使用重载运算符 !=
,它只使用 ==
我认为 returns 它的否定(我在重载函数中添加了一个断点,我的程序不会通过它)。但是,如果我不重载一个或另一个,我就无法编译。这是标准行为吗?我在网上找不到任何相关信息。
我正在使用 Visual Studio 2017 15.5.6,Visual C++ 2017 - 00369-60000-00001-AA639。
它使用 operator==
因为它在 operator!=
中被调用。
它仅使用 operator==
因为 operator!=
可能是 inlined,
instead of executing the function call CPU instruction to transfer control to the function body, a copy of the function body is executed without generating the call.
如果是这种情况,那么您将看不到调用。
还值得注意的是,函数内联与否取决于编译器;不能保证。
Since this meaning of the keyword inline
is non-binding, compilers are free to use inline substitution for any function that's not marked inline, and are free to generate function calls to any function marked inline.
我的代码是这样的
template <typename T>
class FArray
{
/* ... */
inline bool operator == (const FArray& b) const
{
return std::equal(begin(),end(),b.begin());
}
inline bool operator != (const FArray& b) const
{
return !(*this == b);
}
};
然后我有一些单元测试,我正在测试平等和不平等
FArray<double> a, b, c;
/* ... */
ASSERT_TRUE(a == b)
ASSERT_TRUE(a != c)
第二个断言不使用重载运算符 !=
,它只使用 ==
我认为 returns 它的否定(我在重载函数中添加了一个断点,我的程序不会通过它)。但是,如果我不重载一个或另一个,我就无法编译。这是标准行为吗?我在网上找不到任何相关信息。
我正在使用 Visual Studio 2017 15.5.6,Visual C++ 2017 - 00369-60000-00001-AA639。
它使用 operator==
因为它在 operator!=
中被调用。
它仅使用 operator==
因为 operator!=
可能是 inlined,
instead of executing the function call CPU instruction to transfer control to the function body, a copy of the function body is executed without generating the call.
如果是这种情况,那么您将看不到调用。
还值得注意的是,函数内联与否取决于编译器;不能保证。
Since this meaning of the keyword
inline
is non-binding, compilers are free to use inline substitution for any function that's not marked inline, and are free to generate function calls to any function marked inline.