googletest icon indicating copy to clipboard operation
googletest copied to clipboard

[FR]: Add WhenStaticCastTo matcher

Open dkaszews opened this issue 9 months ago • 0 comments

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

dkaszews avatar Jan 30 '25 13:01 dkaszews