c++templatesinheritance

Wrap each base class in a template class


My project breaks down mocks into multiple classes so that they can be maintained in separate files, but then combines together in tests using multiple inheritance, so that you can refer to them using single name. This makes sense to us since each mock is a singleton implementing a global function coming from C API.

Ezample:

class foo_mock;
class bar_mock;
class baz_mock;

class my_test_mock :
    public foo_mock,
    public bar_mock,
    public baz_mock
{};

Unfortunately, due to GMock StrictMock uninteresting function call does not fail a test , when we want a strict mock, instead of just testing::StrictMock<my_test_mock>, you have to wrap each base separately:

class my_test_mock :
    public testing::StrictMock<foo_mock>,
    public testing::StrictMock<bar_mock>,
    public testing::StrictMock<baz_mock>
{};

Is there some way to write a helper which would allow us to write it more compactly? E.g.:

class my_test_mock : inherit_as<testing::StrictMock, foo_mock, bar_mock, baz_mock> {};

Solution

  • You might do:

    template <template <typename> class C, typename ... Ts>
    struct my_test_mock : C<Ts>::type...
    {};
    
    template <typename T>
    struct ToStrictMock
    {
        using type = testing::StrictMock<T>;
    };
    
    using my_nonstrict_test_mock = my_test_mock<std::type_identity,
                                                foo_mock, bar_mock, baz_mock>;
    using my_strict_test_mock = my_test_mock<ToStrictMock,
                                             foo_mock, bar_mock, baz_mock>;
    

    Demo