我有一個界面
class IUObject {
public:
virtual void setProperty(const std::string& name, const std::any& value) = 0;
virtual void setProperty(const std::string& name, std::any&& value) = 0;
};
我創建了模擬物件:
class MockUObject : public IUObject {
public:
MOCK_METHOD(void, setProperty, (const std::string& name, const std::any& value), (override));
MOCK_METHOD(void, setProperty, (const std::string& name, std::any&& value), (override));
};
我需要setProperty通過EXPECT_CALL. 我試過這樣的事情:
MockUObject *mock = new MockUObject();
/// Some code here
EXPECT_CALL(*mock, setProperty(TypedEq<const std::string&>("position"),
TypedEq<std::any&&>(std::any(std::pair<double, double>(6.0, 2.0)))));
但編譯器無法比較std::any:
error: no match for 'operator==' (operand types are 'const std::any' and 'const std::any')
我無法更改基本界面功能,因此我必須使用std::any. 我該如何處理這個問題?
uj5u.com熱心網友回復:
AFAIK,沒有匹配器std::any,所以你需要自己寫。
MATCHER_P(AnyMatcher, value, "")
{
// assume the type of parameter is the same as type stored in std::any,
// will not work e.g. when any stores std::string and you pass a literal
// you'd need to write a template matcher for that case
return std::any_cast<decltype(value)>(arg) == value;
}
用法:
EXPECT_CALL(*mock, setProperty(TypedEq<const std::string&>("position"),
AnyMatcher(std::pair<double, double>(6.0, 2.0))));
在線查看(和一個過往案例)。請注意,在一個函式將const左值參考作為引數而另一個右值參考作為引數的情況下,您不能真正擁有多載,因為這是不明確的(兩者都可以接受右值作為引數)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/325444.html
