如何捕获返回 lambda 的函数的返回值类型?

2024-02-14

鉴于此代码:

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 的好方法?

参考 https://gerrit.libreoffice.org/#/c/71346/6/include/comphelper/flagguard.hxx对于实际代码:

参考 https://ci.libreoffice.org/job/gerrit_mac/31591/consoleFull#-371592627d107d11c-eea5-4209-baa1-fcfb59f7f8a6构建失败:


Use std::declval https://stackoverflow.com/questions/28532781/how-does-stddeclvalt-work带有左值引用bool:

class FlagRestorationGuard :
    public ScopeGuard<decltype(GetFlagRestorationGuard(std::declval<bool&>()))>
{
    ...
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何捕获返回 lambda 的函数的返回值类型? 的相关文章