首页 > 解决方案 > 如何捕获返回 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这?

实际代码参考

参考构建失败:

标签: c++templateslambda

解决方案


std::declval与左值引用一起使用bool

class FlagRestorationGuard :
    public ScopeGuard<decltype(GetFlagRestorationGuard(std::declval<bool&>()))>
{
    ...
};

推荐阅读