Aaron
Aaron

Reputation: 373

Check the type of a generic lambda parameter

I have a generic lambda function that is called with several unrelated structs as its parameter. Inside, I want to execute some code only if the parameter is of a special type.

auto const my_lambda = [](auto obj) {
    // do something with obj
    if (decltype(obj) == SpecialType) // <-- pseudo code, does not work
         auto x = obj.specialMember; // Access to a special member that is present in SpecialType, but not the other types this lambda is called with
}

Upvotes: 1

Views: 839

Answers (1)

Aaron
Aaron

Reputation: 373

The approach with decltype already goes into the right direction.
Two types can be compared with std::is_same_v<Type1, Type2>
To prevent the compiler from complaining about the undefined .specialMember for the other calls, if constexpr is needed.

This amounts to:

auto const my_lambda = [](auto obj) {
    // do something with obj
    if constexpr (std::is_same_v<decltype(obj), SpecialType>)
         auto x = obj.specialMember; // Access to a special member that is present in SpecialType, but not the other types this lambda is called with
}

If the parameter is passed as a reference, an additional std::decay_t is needed to strip the parameter type from any const& and the like.

auto const my_lambda = [](auto const& obj) {
    // do something with obj
    if constexpr (std::is_same_v<std::decay_t<decltype(obj)>, SpecialType>)
         auto x = obj.specialMember; // Access to a special member that is present in SpecialType, but not the other types this lambda is called with
}

Upvotes: 1

Related Questions