如何解决检查通用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)>,but not the other types this lambda is called with
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。