本文介绍了使代码“可转发的转发”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打开了关于转发参考的帖子,这是(希望的)MCVE代码:

I opened this post about forwarding reference, this is a (hopefully) MCVE code:

#include <functional>
#include <vector>

using namespace std;
struct MultiMemoizator {
    template <typename ReturnType, typename... Args>
    ReturnType callFunction(std::function<ReturnType(Args...)> memFunc, Args&&... args) {

    }
};

typedef vector<double> vecD;

vecD sort_vec (const vecD& vec) {
    return vec;
}

int main()
{
    vecD vec;
    std::function<vecD(const vecD&)> sortFunc(sort_vec);
    MultiMemoizator mem;
    mem.callFunction<vecD, vecD>(sortFunc, vec);
}

由于这不是整个代码,也许我必须添加额外

Since this is not the whole code, maybe I'll have to add extra code based on the answers.

无论如何,如此因为 Args 没有推导出来。

Anyway, as was suggested in this answer, forwarding reference is not possible with this version, since Args is not deduced.

所以我的问题是:可以让这个代码转发引用?

So my question is: is it possible to make this code "forwarding referencable"?

推荐答案

为了完美转发你的参数,以推导出类型。你可以通过分别推导函数的参数和函数的参数来实现这一点:

In order to perfect-forward your arguments, you need to have the types deduced. You can do this by deducing the arguments to the function and the parameters to the functor separately:

template <typename ReturnType, typename... FunArgs, typename... Args>
ReturnType callFunction(std::function<ReturnType(FunArgs...)> memFunc,
                        Args&&... args) 
{
    //...
}

然后你可以调用 callFunction 没有模板参数,并有一切推论:

Then you can call callFunction without template parameters and have everything deduced:

mem.callFunction(sortFunc, vec);

这篇关于使代码“可转发的转发”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!