c++ - 如何捕获返回 lambda 的函数的返回值类型?
问题描述
鉴于此代码:
template <class Func> class ScopeGuard
{
public:
/** @param func function object to be executed in dtor
*/
explicit ScopeGuard( Func && func ) : m_func( std::move(func) ) {}
~ScopeGuard()
{
if (m_bDismissed)
return;
m_func();
}
/** Dismisses the scope guard, i.e. the function won't
be executed.
*/
void dismiss() { m_bDismissed = true; }
private:
// noncopyable until we have good reasons...
ScopeGuard(const ScopeGuard&) = delete;
ScopeGuard& operator=(const ScopeGuard&) = delete;
Func m_func;
bool m_bDismissed = false;
};
// Get functor for cleanup to use in FlagRestorationGuard
auto GetFlagRestorationGuard(bool& i_flagRef)
{
return [&i_flagRef, resetVal = i_flagRef] { i_flagRef = resetVal; };
}
class FlagRestorationGuard : public ScopeGuard<decltype(GetFlagRestorationGuard(*(new bool)))>
{
public:
FlagRestorationGuard( bool& i_flagRef, bool i_temporaryValue )
: ScopeGuard(GetFlagRestorationGuard(i_flagRef))
{
i_flagRef = i_temporaryValue;
}
};
使用 Apple Clang 构建时出现以下错误GetFlagRestorationGuard(*(new bool))
:
错误:具有副作用的表达式在未评估的上下文中无效 [-Werror,-Wunevaluated-expression]
请注意,此代码可以在 MSVC 2017 中构建并正常工作。当然,可以重新编写它以使用结构operator()()
而不是 lambda 和返回它的函数,但我想知道是否有一种很好的方法来使用 lambda这?
参考构建失败:
解决方案
std::declval
与左值引用一起使用bool
:
class FlagRestorationGuard :
public ScopeGuard<decltype(GetFlagRestorationGuard(std::declval<bool&>()))>
{
...
};
推荐阅读
- firebase - 在 Firebase 云消息 (FCM) 主题订阅中,“addDate”逻辑不确定
- python - 在 .bat 文件中使用 Python 导入 pandas 时不起作用
- dom - 绝对定位的 div 元素会影响文档流结构。为什么?
- sql - SQL 匹配持续时间(从日期时间到日期时间)
- security - 在整个域林中阻止 netcat
- keycloak - Duo 代理作为 LDAP 用户联合密钥斗篷
- neo4j - Neo4J Bloom 不显示属性或类别
- ruby-on-rails - 在heroku上成功部署后Rails应用程序无法正常工作?
- oracle - Spring JPA 标准生成器大于:我可以传递字符串值以比较数据库中的数字类型吗
- ibm-midrange - AS400 中的 Json_table