如何保证在调用函数对象时参数求值的顺序

如何保证在调用函数对象时参数求值的顺序

本文介绍了如何保证在调用函数对象时参数求值的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

时避免未定义的构造函数执行顺序的问题的答案导致了在讨论期间,我了解到可以为构造函数保证参数求值的顺序:使用
braced-init-list ,顺序将保证从左到右:

The answers to the question on how to avoid undefined execution order for the constructors when using std::make_tuple led to a discussion during which I learned that the order of argument evaluation can be guaranteed for constructors: Using a braced-init-list the order is guaranteed to be left to right:

T{ a, b, c }

表达式 a b c 以给定的顺序评估。这是这种情况,即使 T 只有一个正常的构造函数定义。

The expressions a, b, and c are evaluated in the given order. This is the case, even if the type T just has a normal constructor defined.

显然,是一个构造函数,有时在调用函数时保证求值的顺序是很好的,但是没有诸如 brace-argument-list 这样的函数来调用具有定义的参数求值顺序的函数。问题是:可以使用构造函数的保证来建立一个函数调用设施( function_apply()

Clearly, not everything called is a constructor and sometimes it would be nice to guarantee the order of evaluation when calling a function but there is no such thing as brace-argument-list to call function with a defined order of evaluation of their arguments. The question becomes: Can the guarantees to constructors be used to build a function call facility ("function_apply()") with an ordering guarantee for the evaluation of arguments? It is acceptable to require a function object being called.

推荐答案

一个愚蠢的包装类如下:

What about a silly wrapper class like this:

struct OrderedCall
{
    template <typename F, typename ...Args>
    OrderedCall(F && f, Args &&... args)
    {
        std::forward<F>(f)(std::forward<Args>(args)...);
    }
};

用法:

void foo(int, char, bool);

OrderedCall{foo, 5, 'x', false};

如果你想要一个返回值,你可以通过引用传递它以提取返回类型),或将其存储在对象中,以获得如下接口:

If you want a return value, you could pass it in by reference (you'll need some trait to extract the return type), or store it in the object, to get an interface like:

auto x = OrderedCall{foo, 5, 'x', false}.get_result();

这篇关于如何保证在调用函数对象时参数求值的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 09:17