有 gtest 比较二进制的东西吗?

Has gtest something that compares binary?

Google Test比较对给定对象的二进制表示进行操作的函数吗?

我有两个相同类型的 struct-对象,但没有比较功能。 struct 是普通旧数据类型 (POD),因此二进制比较可以工作。

我需要这样的东西:

struct A{
  int some_data;
};

TEST(test, case){
    A a1{0}, a2{1};
    EXPECT_BINARY_EQ(a1, a2);
}

在 C++ 中使用 gtest 执行此操作的最简单方法是什么。

我的建议基于:http://en.cppreference.com/w/cpp/language/operators

您可以使用 std::tie(来自元组 header)在 class 上定义 operator ==

struct Record
{
    std::string name;
    unsigned int floor;
    double weight;

    friend bool operator ==(const Record& l, const Record& r)
    {
        return   std::tie(l.name, l.floor, l.weight)
              == std::tie(r.name, r.floor, r.weight); // keep the same order
    }
};

我目前的解决方案:

#include <algorithm>

template < typename T >
bool binary_eq(T const& lhs, T const& rhs){
    auto lhs_i = reinterpret_cast< char const* >(&lhs);
    auto rhs_i = reinterpret_cast< char const* >(&rhs);
    return std::equal(lhs_i, lhs_i + sizeof(T), rhs_i);
}

编辑:

感谢 Erik Alapää 和 Frank 我知道这不能通用,因为 struct 成员的填充。在我的具体情况下它确实有效,因为所有成员都是 double 的。

如果可以使用 magic_get 库:

// requires: C++14, MSVC C++17
#include <iostream>
#include "boost/pfr/precise.hpp"

struct my_struct
{ // no operators defined!
    int    i;
    char   c;
    double d;
};

bool operator==(const my_struct& l, const my_struct& r)
{
    using namespace boost::pfr::ops; // out-of-the-box operators for all PODs!

    return boost::pfr::structure_tie( l ) == boost::pfr::structure_tie( r );
}

int main()
{
    my_struct s{ 100, 'H', 3.141593 };
    my_struct t{ 200, 'X', 1.234567 };

    std::cout << ( s == s ) << '\n' << ( s == t ) << "\n";
}

通过在Google中定义operator ==ASSERT_EQ测试可以使用:

TEST( Test_magic_get, Test_magic_get )
{
    my_struct s{ 100, 'H', 3.141593 };
    my_struct t{ 200, 'X', 1.234567 };

    //ASSERT_EQ( s, t );
    ASSERT_EQ( s, s );
}