假设我有这个类并且在 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/