Overloaded methods is ambiguous.

Posted on

オーバーロードしている関数で引数の数まで同じだと、悲しいことになる。

例えば、

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <gmock/gmock.h>

using ::testing::Eq;
using ::testing::Return;
using ::testing::Matcher;

class X {
public:
    bool operator==(const X& other) const { return false; }
};

class Y {
public:
    bool operator==(const Y& other) const { return false; }
};

class Foo {
public:
    virtual ~Foo() { }

    virtual void function(X x) { }
    virtual void function(Y x) { }
};

class Mock : public Foo {
public:
    MOCK_METHOD1(function, void(X));
    MOCK_METHOD1(function, void(Y));
};

TEST(MockTest, Call_Foo_X) {
    Mock m;

    X arg;

    EXPECT_CALL(m, function(Eq(arg))).WillOnce(Return());
}

これをコンパイルすると

1
2
3
4
5
6
7
$ g++ -I/opt/vendor/include -L/opt/vendor/lib -lgtest -lgmock -c ambiguous.cc
ambiguous.cc:11: error: ISO C++ forbids declaration of ‘Interface’ with no type
ambiguous.cc:23: error: multiple types in one declaration
ambiguous.cc: In member function ‘virtual void MockTest_Call_Foo_X_Test::TestBody()’:
ambiguous.cc:28: error: call of overloaded ‘gmock_function(testing::internal::EqMatcher<x>)’ is ambiguous
ambiguous.cc:19: note: candidates are: testing::internal::MockSpec<void(X)>& Mock::gmock_function(const testing::Matcher<x>&)
ambiguous.cc:20: note:                 testing::internal::MockSpec<void(Y)>& Mock::gmock_function(const testing::Matcher<y>&)

ambiguousですよ。ambiguous!

で、どうすっかって。

1
EXPECT_CALL(m, function(Matcher<X>(Eq(arg)))).WillOnce(Return());

明示的にMatcherで型を示してあげると。