c ++ 11:模板化包装函数 [英] c++11: Templated wrapper function

查看:71
本文介绍了c ++ 11:模板化包装函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试创建一个通用包装函数,该函数将任何函数作为参数以及它们的参数。就像 std :: thread 构造函数一样。

I try to create a general wrapper function which takes any function as argument and also their parameters. Just something like the std::thread constructor.

我当前的代码是:

#include <iostream>

using namespace std;

template<typename FUNCTION, typename... ARGS>
void wrapper(FUNCTION&& func, ARGS&&... args)
{
    cout << "WRAPPER: BEFORE" << endl;
    auto res = func(args...);
    cout << "WRAPPER: AFTER" << endl;
    //return res;
}

int dummy(int a, int b)
{
    cout << a << '+' << b << '=' << (a + b) << endl;
    return a + b;
}

int main(void)
{
    dummy(3, 4);
    wrapper(dummy, 3, 4);
}

包装函数本身可以工作。它使用给定的参数调用给定的函数对象( std :: function ,函子或仅是正常函数)。但是我也想返回它的返回值。

The wrapper function itself works. It calls the given function object (std::function, functor or just a "normal" function) with the given arguments. But i also like to return its return value.

这应该与删除的 return 语句一起工作,但不幸的是我不知道如何声明包装函数的返回类型。

This should work with the removed return-statement, but unfortunately i dont know how to declare the wrapper functions return type.

我尝试了很多事情(例如,使用 decltype ),但没有任何效果。现在的问题是,我如何运行以下代码?

I tried many things (e.g. with decltype), but nothing worked. My question is now, how i get the following code running?

#include <iostream>

template<typename FUNCTION, typename... ARGS>
??? wrapper(FUNCTION&& func, ARGS&&... args)
{
    cout << "WRAPPER: BEFORE" << endl;
    auto res = func(args...);
    cout << "WRAPPER: AFTER" << endl;
    return res;
}

int dummy(int a, int b)
{
    cout << a << '+' << b << '=' << (a + b) << endl;
    return a + b;
}

int main(void)
{
    dummy(3, 4);
    cout << "WRAPPERS RES IS: " << wrapper(dummy, 3, 4) << endl;
}

我认为代码应该可以工作,但除外???

I think the code should work, except for the ???.

感谢您的任何想法

感谢
Kevin

Regards Kevin

推荐答案

使用 std :: result_of

template <typename F, typename ...Args>
typename std::result_of<F &&(Args &&...)>::type wrapper(F && f, Args &&... args)
{
    return std::forward<F>(f)(std::forward<Args>(args)...);
}

在C ++ 14中,您可以使用 result_of_t 别名:

In C++14 you can use the result_of_t alias:

template <typename F, typename ...Args>
std::result_of_t<F &&(Args &&...)> wrapper(F && f, Args &&... args)
{
    return std::forward<F>(f)(std::forward<Args>(args)...);
}

或者您可以使用返回类型推导:

Or you can use return type deduction:

template <typename F, typename ...Args>
decltype(auto) wrapper(F && f, Args &&... args)
{
    std::cout << "before\n";
    auto && res = std::forward<F>(f)(std::forward<Args>(args)...);
    std::cout << "after\n";
    return res;
}

这篇关于c ++ 11:模板化包装函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆