Skip to content

[FR]: Add WhenStaticCastTo matcher #4710

Open
@dkaszews

Description

@dkaszews

Does the feature exist in the most recent commit?

No

Why do we need this feature?

The existing (Safe)MatcherCast and WhenDynamicCastTo do not work well for pointers such as void*, since the former requires the underlying types to be convertible (void => T) and the second simply does not allow void* as the argument.

This is especially needed when mocking APIs which type-erase their arguments as void*, e.g. something like int api(enum message_type type, void* arg).

Example usage:

const auto matcher = WhenStaticCastTo<ReadMessage*>(Field(&ReadMessage::length, 10));
EXPECT_CALL(mock, api(ReadMessageId, matcher)).WillOnce(Return(0));

Describe the proposal.

I was perfectly able to get the expected behavior by simply duplicating all of WhenDynamicCastTo with its underlying implementation and just switching dynamic_cast to static_cast with the corresponding message. Real implementation should probably avoid such duplication and instead just abstract away the casting into something like:

struct static_caster {
    static constexpr const char* name = "static";
    template <typename To, typename From>
    To cast(From* from) { return static_cast<To>(from); }
    // plus overload references
};

// same for dynamic

Other types of casts such as reinterpret, const and C++20 bit should also be considered.

Is the feature specific to an operating system, compiler, or build system version?

No

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions