c++ - gmock 和转发声明的类

标签 c++ forward-declaration googlemock

假设我有这个类并且在 Base.h 中向前声明了类型管理器。

#include <Base.h>

class MockBase : public Base
{
public:
    MOCK_CONST_METHOD0( manager, const Manager&( ) );
    ...
};

我不会在我的测试中使用这个方法,所以我不想将 Manager 类的定义包含到带有测试的文件中。

但我认为在编译 gmock 时会尝试准备错误消息并且在其内部深处它需要 Manager 变量的地址并且我有一个错误:

error C2027: use of undefined type 'Manager' \external\googlemock\gtest\include\gtest\gtest-printers.h 146 1

我能否以某种方式避免包含包含我不会使用的方法的前向声明类型定义的文件?

最佳答案

想法是为 UT 定义一个通用的 ostream 运算符,它只对前向声明的类型激活。它必须位于全局 namespace 中。如果包含,它将解决所有类型的前向声明 gmock 问题。
用户仍然可以提供自定义的 PrintTo 函数,即使对于前向声明的引用也是如此,因为 PrintTo 似乎首先被调用。它适用于 GCC 中的 gmock 1.7 和 C++14

// A class to determine if definition of a type is available or is it forward declared only
template <class, class = void>
struct IsDefined : std::false_type
{};

template <class T>
struct IsDefined<T, std::enable_if_t<std::is_object<T>::value 
                                     && not std::is_pointer<T>::value 
                                     && (sizeof(T) > 0)>>
    : std::true_type
{};

// It has to be in global namespace
template <
    typename T,
    typename = std::enable_if_t<
        not IsDefined<T>::value and 
        not std::is_pointer<T>::value and 
        std::is_object<T>::value>>
std::ostream& operator<<(std::ostream& os, const T& ref)
{
    os << "Forward declared ref: " << static_cast<const void*>(&ref);
    // assert(false); // Could assert here as we do not want it to be executed
    return os;
}

关于c++ - gmock 和转发声明的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35746599/

相关文章:

c++ - 元组中的前向声明和交叉引用

googlemock - 带有变量的 SetArgPointee

c++ - gmock 可以模拟重载方法吗?

c++ - 谷歌模拟 : Mock private variable member that is instantiated in target class's constructor

c++ - 具有 ifstream 成员的内部类的构造函数返回无效的 fstream

c++ - 在 iOS 应用程序中链接静态库后架构 arm64 的 undefined symbol

C++ 前向类声明

c++ - C++ 中的函数行为

c++ - 新的 c++11 for 循环导致 : "error: ‘begin’ was not declared in this scope"

c++ - 为什么嵌套类的成员函数不需要完整类型?