c++ - 为什么 gtest 看不到 == 的定义?

标签 c++ templates googletest

我有一个模板类Matrix:

    template<typename T>
    class Matrix {
        //blah-blah-blah
        }

以及以下运算符:

template<typename T>
bool operator==(const Matrixes::Matrix<T> &lhs, const Matrixes::Matrix<T> &rhs) {
    if (lhs.get_cols()!=rhs.get_cols() || lhs.get_rows()!=rhs.get_rows()){
        return false;
    }
    for (int r = 0; r < lhs.get_rows(); ++r) {
        for (int c = 0; c < lhs.get_cols(); ++c) {
            if (lhs.get(r, c) != rhs.get(r, c)) {
                return false;
            }
        }

    }
    return true;
}

上述运算符是在Matrixes命名空间之外定义的。

我有一些测试(我正在使用框架 Google Tests)。但是,如果我写这样的内容:

TEST(MatrixOperations, MatrixMultiplicationSimple) {
    Matrixes::Primitives<int>::VectorMatrix vec1{{{8, 3, 5, 3, 8}, {5, 2, 0, 5, 8}, {0, 3, 8, 8, 1}, {3, 0, 0, 5, 0}, {2, 7, 5, 9, 0}}};
    Matrixes::Primitives<int>::VectorMatrix vec2{{{3, 1, 7, 2, 9}, {4, 6, 2, 4, 5}, {2, 5, 9, 4, 6}, {5, 3, 3, 1, 2}, {1, 8, 2, 6, 8}}};
    Matrixes::Matrix<int> vec1m{vec1};
    Matrixes::Matrix<int> vec2m{vec2};
    Matrixes::Matrix<int> matrix_out_ref{{{69, 124, 132, 99, 187}, {56, 96, 70, 71, 129}, {69, 90, 104, 58, 87}, {34, 18, 36, 11, 37}, {89, 96, 100, 61, 101}}};
    Matrixes::Matrix<int> matrix_out_fact = vec1m * vec2m;
    bool t = matrix_out_fact == matrix_out_ref;
    EXPECT_EQ(t, true);
}

一切正常。请注意,我在这里“手动”使用 operator==:

 bool t = matrix_out_fact == matrix_out_ref;
 EXPECT_EQ(t, true);

但是,如果我不写这两行,而是写如下内容:

EXPECT_EQ(matrix_ou_fact, matrix_out_ref);

我收到编译错误:

/usr/local/include/gtest/gtest.h:1522:11: error: no match for ‘operator==’ (operand types are ‘const Matrixes::Matrix<int>’ and ‘const Matrixes::Matrix<int>’)
   if (lhs == rhs) {

为什么gtest“看不到”operator==的定义?

谢谢

最佳答案

EXPECT_EQ 中的比较发生在与您的直接测试用例不同的范围内。它通过argument dependent lookup查找需要调用的运算符函数。 (ADL)。由于您的运算符函数与您的类不在同一命名空间中,因此 ADL 不会拾取它。

它在您的直接测试用例中起作用,因为您可能以适当的顺序包含适当的 header ,以便查找运算符不依赖于 ADL。但Gtest框架的实现必须依赖于ADL。

所以修复很简单。将自定义运算符移至Matrixes 命名空间中。它是类的公共(public)接口(interface)的一部分,因此无论如何它都属于同一个命名空间。

关于c++ - 为什么 gtest 看不到 == 的定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55208235/

相关文章:

C++ 返回数组并将其分配给变量

c++ - 如何处理老年人糟糕的编码风格/实践?

具有默认参数的 C++ 模板类,可能还有元编程

c++ - Axter EzLogger - 如何删除警告或错误消息? i686-apple-darwin10-g++-4.2.1 (海湾合作委员会) 4.2.1

c++ - 模板类型方法 GTesting

c++ - 如何将 Cppunit 测试迁移到 GoogleTest?

c++ - c++中std::min(int)的效率

c++ - 为什么不构造内部类? C++

cmake - 将 Googletest 添加到现有的 CMake 项目

c++ - 调试后 Visual Studio 拒绝暂停