32

(这是对“`decltype(auto)` 变量有任何实际用例吗?后续报道)

考虑以下场景 - 我想将一个函数传递f给另一个函数invoke_log_return,该函数将:

  1. 调用f

  2. 打印一些东西到标准输出

  3. 返回 的结果f,避免不必要的复制/移动并允许复制省略。

请注意,如果f抛出,则不应将任何内容打印到stdout。这是我到目前为止所拥有的:

template <typename F>
decltype(auto) invoke_log_return(F&& f)
{
    decltype(auto) result{std::forward<F>(f)()};
    std::printf("    ...logging here...\n");

    if constexpr(std::is_reference_v<decltype(result)>)
    {
        return decltype(result)(result);
    }
    else
    {
        return result;
    }
}

让我们考虑各种可能性:

  • f返回纯右值时:

    • result将是一个对象;

    • invoke_log_return(f)将是一个prvalue(有资格进行复制省略)。

  • f返回左值xvalue时:

    • result将作为参考;

    • invoke_log_return(f)将是左值xvalue

您可以在 godbolt.org 上看到一个测试应用程序。如您所见,对纯右值情况g++执行 NRVO clang++没有。

问题:

  • 这是decltype(auto)从函数中“完美”返回变量的最短方法吗?有没有更简单的方法来实现我想要的?

  • 可以将if constexpr { ... } else { ... }模式提取到单独的函数中吗?提取它的唯一方法似乎是宏。

  • 有什么好的理由clang++不为上述prvalue案例执行NRVO?应该将其报告为潜在的增强功能,还是g++NRVO 优化在这里不合法?


这是使用助手的替代方法on_scope_success(如 Barry Revzin 所建议):

template <typename F>
struct on_scope_success : F
{
    int _uncaught{std::uncaught_exceptions()};

    on_scope_success(F&& f) : F{std::forward<F>(f)} { }

    ~on_scope_success()
    {
        if(_uncaught == std::uncaught_exceptions()) {
            (*this)();
        }
    }
};

template <typename F>
decltype(auto) invoke_log_return_scope(F&& f)
{
    on_scope_success _{[]{ std::printf("    ...logging here...\n"); }};
    return std::forward<F>(f)();
}

虽然invoke_log_return_scope要短得多,但这需要函数行为的不同心智模型和新抽象的实现。令人惊讶的是,两者都g++使用clang++此解决方案执行 RVO/复制省略。

godbolt.org 上的实时示例

正如Ben Voigt所提到的,这种方法的一个主要缺点是 的返回值f不能是日志消息的一部分。

4

3 回答 3

4

这是最简单、最清晰的写法:

template <typename F>
auto invoke_log_return(F&& f)
{ 
    auto result = f();
    std::printf("    ...logging here... %s\n", result.foo());    
    return result;
}

GCC 得到了正确的(没有不必要的复制或移动)预期结果:

    s()

in main

prvalue
    s()
    ...logging here... Foo!

lvalue
    s(const s&)
    ...logging here... Foo!

xvalue
    s(s&&)
    ...logging here... Foo!

因此,如果代码清晰,具有相同的功能,但没有像竞争对手那样优化运行,这是编译器优化失败,clang 应该解决它。这是在工具中解决的更有意义的问题,而不是应用层实现。

https://gcc.godbolt.org/z/50u-hT

于 2019-08-21T01:17:43.040 回答
3

我们可以使用 : 的修改版本std::forward(避免名称转发以防止 ADL 问题)

template <typename T>
T my_forward(std::remove_reference_t<T>& arg)
{
    return std::forward<T>(arg);
}

此函数模板用于转发decltype(auto)变量。它可以这样使用:

template <typename F>
decltype(auto) invoke_log_return(F&& f)
{
    decltype(auto) result{std::forward<F>(f)()};
    std::printf("    ...logging here...\n");
    return my_forward<decltype(result)>(result);
}

这样,如果std::forward<F>(f)()返回

  • prvalue,result则为非引用,invoke_log_return返回非引用类型;

  • 一个左值,然后result是一个左值引用,并invoke_log_return返回一个左值引用类型;

  • 一个 xvalue,然后result是一个右值引用,并invoke_log_return返回一个右值引用类型。

(基本上是从我的https://stackoverflow.com/a/57440814复制的)

于 2019-08-19T18:06:39.090 回答
1

Q1:“这是从函数中“完美”返回 decltype(auto) 变量的最短方法吗?有没有更简单的方法来实现我想要的?

好吧,证明最优性总是很困难,但你的第一个解决方案已经很短了。实际上,您唯一希望删除的是if constexpr- 其他一切都是必要的(不改变问题的重点)。

您的第二个解决方案以一些额外的心理扭曲和无法在 log 语句中使用变量为代价解决了这个问题 - 或者,更一般地说,它只使您能够执行与您的结果无关的操作。

@david-kennedy 的简单解决方案通过创建一个纯右值,然后可以复制到其最终存储位置,巧妙地解决了这个问题。如果您的用例支持此模型并且您使用 GCC,那么它几乎是最好的解决方案:

template <typename F>
auto invoke_log_return(F&& f)
{ 
    auto result = f();
    std::printf("    ...logging here...\n");    
    return result;
}

然而,这个解决方案根本没有实现完美转发,因为它的返回值与包装函数的类型不同(它剥离了引用)。除了成为潜在错误(int& a = f();vs. int& a = wrapper(f);)的来源之外,这还会导致至少执行一个副本。

为了证明这一点,我修改了测试工具,使其本身不执行任何复制。因此,此 GCC 输出显示包装器本身完成的副本(clang 执行更多的复制/移动操作):

    s()
in main

prvalue
    s()
    ...logging here...

lvalue
    s(const s&)
    ...logging here...

xvalue
    s(s&&)
    ...logging here...

https://gcc.godbolt.org/z/dfrYT8

但是,可以创建一个在 GCC 和 clang 上执行零复制/移动操作的解决方案,方法是摆脱if constexpr不同的实现并将不同的实现移动到两个通过 区分的函数中enable_if

template <typename F>
auto invoke_log_return(F&& f)
    -> std::enable_if_t<
        std::is_reference_v<decltype(std::forward<F>(f)())>,
        decltype(std::forward<F>(f)())
    >
{
    decltype(auto) result{std::forward<F>(f)()};
    std::printf("    ...logging glvalue...\n");
    return decltype(result)(result);
}

template <typename F>
auto invoke_log_return(F&& f)
    -> std::enable_if_t<
        !std::is_reference_v<decltype(std::forward<F>(f)())>,
        decltype(std::forward<F>(f)())
    >
{
    decltype(auto) result{std::forward<F>(f)()};
    std::printf("    ...logging prvalue...\n");
    return result;
}

零拷贝:

    s()
in main

prvalue
    s()
    ...logging prvalue...

lvalue
    ...logging glvalue...

xvalue
    ...logging glvalue...

https://gcc.godbolt.org/z/YKrhbs

现在,当然,与原始解决方案相比,这增加了行数,即使它返回的变量可以说是“更完美”(在 NRVO 由两个编译器执行的意义上)。将功能提取到实用函数中会导致您的第二个问题。

Q2:“可以将if constexpr { ... } else { ... }模式提取到单独的函数中吗?提取它的唯一方法似乎是宏。”

不,因为您不能省略将纯右值传递给函数,这意味着传递result给函数将导致复制/移动。对于 glvalues,这不是问题(如 所示std::forward)。

但是,可以稍微改变之前解决方案的控制流程,使其本身可以用作库函数:

template <typename F>
decltype(auto) invoke_log_return(F&& f) {
    return invoke_return(std::forward<F>(f), [](auto&& s) {
        std::printf("    ...logging value at %p...", static_cast<void*>(&s));
    });
}

https://gcc.godbolt.org/z/c5q93c

这个想法是使用该enable_if解决方案来提供一个函数,该函数采用生成器函数和一个附加函数,然后可以对临时值进行操作——无论是纯右值、xvalue 还是 lvalue。库函数可能如下所示:

template <typename F, typename G>
auto invoke_return(F&& f, G&& g)
    -> std::enable_if_t<
        std::is_reference_v<decltype(std::forward<F>(f)())>,
        decltype(std::forward<F>(f)())
    >
{
    decltype(auto) result{std::forward<F>(f)()};
    std::forward<G>(g)(decltype(result)(result));
    return decltype(result)(result);
}

template <typename F, typename G>
auto invoke_return(F&& f, G&& g)
    -> std::enable_if_t<
        !std::is_reference_v<decltype(std::forward<F>(f)())>,
        decltype(std::forward<F>(f)())
    >
{
    decltype(auto) result{std::forward<F>(f)()};
    std::forward<G>(g)(result);
    return result;
}

Q3:“clang++ 对上述prvalue情况不执行NRVO有什么好的理由吗?应该报告为潜在的增强,还是g++的NRVO优化在这里不合法?”

检查我的 C++2a 草案(N4835 §11.10.5/1.1 [class.copy.elision]),NRVO 的表述非常简单:

  • return具有类返回类型的函数 [check] 中的语句 [check] [函数模板实例化为返回的函数s,所以 check],当表达式是非易失性的名称时 [check] 自动 [check]与函数返回类型 [check] 具有相同类型(忽略 cv 限定)的对象(除了 * handler* (14.4) [check]的异常声明引入的函数参数或变量),复制 /通过将自动对象直接构造到函数调用的返回对象中,可以省略移动操作。

我不知道这应该是无效的任何其他原因。

于 2020-08-08T20:56:33.690 回答