首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在调用函数对象时,如何保证参数求值的顺序?

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

Stack Overflow用户
提问于 2012-12-28 01:21:47
回答 3查看 2.3K关注 0票数 19

关于how to avoid undefined execution order for the constructors when using std::make_tuple的问题的答案引发了一场讨论,在讨论中我了解到,对于构造函数,参数求值的顺序是可以保证的:使用带括号的初始化列表,可以保证顺序从左到右:

代码语言:javascript
复制
T{ a, b, c }

按照给定的顺序计算表达式abc。情况就是这样,即使类型T只定义了一个普通的构造函数。

显然,并不是所有被调用的都是构造函数,有时在调用函数时保证求值顺序是很好的,但没有花括号-参数-列表这样的东西来调用函数,并定义了参数求值的顺序。问题变成了:构造函数的保证是否可以用来构建函数调用工具("function_apply()"),并为参数的求值提供排序保证?要求调用一个函数对象是可以接受的。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-12-28 01:25:16

像这样一个愚蠢的包装器类怎么样:

代码语言:javascript
复制
struct OrderedCall
{
    template <typename F, typename ...Args>
    OrderedCall(F && f, Args &&... args)
    {
        std::forward<F>(f)(std::forward<Args>(args)...);
    }
};

用法:

代码语言:javascript
复制
void foo(int, char, bool);

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

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

代码语言:javascript
复制
auto x = OrderedCall{foo, 5, 'x', false}.get_result();
票数 15
EN

Stack Overflow用户

发布于 2012-12-28 02:02:14

我提出的解决方案使用std::tuple<...>将参数组合在一起,然后使用此对象的元素调用函数对象。优点是它可以推导出返回类型。实际的具体逻辑如下所示:

代码语言:javascript
复制
template <typename F, typename T, int... I>
auto function_apply(F&& f, T&& t, indices<I...> const*)
    -> decltype(f(std::get<I>(t)...)) {
    f(std::get<I>(t)...);
}

template <typename F, typename T>
auto function_apply(F&& f, T&& t)
    -> decltype(function_apply(std::forward<F>(f), std::forward<T>(t),
                               make_indices<T>())) {
    function_apply(std::forward<F>(f), std::forward<T>(t),
                   make_indices<T>());
}

..。它使用如下表达式调用:

代码语言:javascript
复制
void f(int i, double d, bool b) {
    std::cout << "i=" << i << " d=" << d << " b=" << b << '\n';
}

int fi() { std::cout << "int\n"; return 1; }
double fd() { std::cout << "double\n"; return 2.1; }
bool fb() { std::cout << "bool\n"; return true; }

int main()
{
    std::cout << std::boolalpha;
    function_apply(&f, std::tuple<int, double, bool>{ fi(), fd(), fb() });
}

这种方法的主要缺点是需要指定std::tuple<...>的元素。另一个问题是MacOS上当前版本的clang调用函数的顺序与它们出现的顺序相反,即不遵守带括号的初始化列表中的求值顺序(这是gcc的一个错误)或不存在(即,我误解了使用带括号的初始化列表的保证。在同一平台上,clang以预期的顺序执行函数。

使用的函数make_indices()只创建了一个指向类型为indices<I...>的对象的适当指针,该对象具有一系列可用于std::tuple<...>的索引

代码语言:javascript
复制
template <int... Indices> struct indices;
template <> struct indices<-1> { typedef indices<> type; };
template <int... Indices>
struct indices<0, Indices...>
{
    typedef indices<0, Indices...> type;
};
template <int Index, int... Indices>
struct indices<Index, Indices...>
{
    typedef typename indices<Index - 1, Index, Indices...>::type type;
};

template <typename T>
typename indices<std::tuple_size<T>::value - 1>::type const*
make_indices()
{
    return 0;
}
票数 5
EN

Stack Overflow用户

发布于 2012-12-28 02:59:40

首先,我认为如果顺序很重要,最好在调用之前显式构造这些元素,然后传递它们。读起来容易多了,但趣味性却差得多!

这只是对Kerrek的回答的扩展:

代码语言:javascript
复制
#include <utility>

namespace detail
{
    // the ultimate end result of the call;
    // replaceable with std::result_of? I do not know.
    template <typename F, typename... Args>
    static auto ordered_call_result(F&& f, Args&&... args)
        -> decltype(std::forward<F>(f)
                    (std::forward<Args>(args)...)); // not defined

    template <typename R>
    class ordered_call_helper
    {
    public:
        template <typename F, typename... Args>
        ordered_call_helper(F&& f, Args&&... args) :
        mResult(std::forward<F>(f)(std::forward<Args>(args)...))
        {}

        operator R()
        {
            return std::move(mResult);
        }

    private:
        R mResult;
    };

    template <>
    class ordered_call_helper<void>
    {
    public:
        template <typename F, typename... Args>
        ordered_call_helper(F&& f, Args&&... args)
        {
            std::forward<F>(f)(std::forward<Args>(args)...);
        }
    };

    // perform the call then coax out the result member via static_cast,
    // which also works nicely when the result type is void (doing nothing)
    #define ORDERED_CALL_DETAIL(r, f, ...) \
            static_cast<r>(detail::ordered_call_helper<r>{f, __VA_ARGS__})
};

// small level of indirection because we specify the result type twice
#define ORDERED_CALL(f, ...) \
        ORDERED_CALL_DETAIL(decltype(detail::ordered_call_result(f, __VA_ARGS__)), \
                            f, __VA_ARGS__)

下面是一个例子:

代码语言:javascript
复制
#include <iostream>

int add(int x, int y, int z)
{
    return x + y + z;
}

void print(int x, int y, int z)
{
    std::cout << "x: " << x << " y: " << y << " z: " << z << std::endl;
}

int get_x() { std::cout << "[x]"; return 11; }
int get_y() { std::cout << "[y]"; return 16; }
int get_z() { std::cout << "[z]"; return 12; }

int main()
{
    print(get_x(), get_y(), get_z());
    std::cout << "sum: " << add(get_x(), get_y(), get_z()) << std::endl;

    std::cout << std::endl;   

    ORDERED_CALL(print, get_x(), get_y(), get_z());
    std::cout << "sum: " << ORDERED_CALL(add, get_x(), get_y(), get_z()) << std::endl;

    std::cout << std::endl;

    int verify[] = { get_x(), get_y(), get_z() };
}

最后一行用于验证花括号初始值设定项是否确实有效。

不幸的是,正如从其他答案/评论中发现的那样,GCC没有答对,所以我无法测试我的答案。此外,MSVC Nov2012CTP也不能正确处理(并且有一个令人讨厌的bug,会在ordered_call_result†上阻塞)。如果有人想用clang来测试这一点,那就太好了。

对于这个特定的例子,尾随返回类型可以是decltype(f(0, 0, 0))†。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14058592

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档