检查泛型lambda参数的类型



我有一个通用的lambda函数,它是用几个不相关的结构作为参数来调用的。在内部,我只想在参数是特殊类型的情况下执行一些代码。

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
}

使用decltype的方法已经朝着正确的方向发展
两种类型可以与std::is_same_v<Type1, Type2>进行比较
为了防止编译器抱怨其他调用的未定义.specialMember,需要if constexpr

这相当于:

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
}

如果参数作为引用传递,则需要额外的std::decay_t来从任何const&等中剥离参数类型。

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
}

最新更新