繁体   English   中英

c ++ 11:模板化包装函数

[英]c++11: Templated wrapper function

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

我目前的代码是:

#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 ,functor或只是“普通”函数)。 但我也想返回它的返回值。

这应该与删除的return -statement一起使用,但不幸的是我不知道如何声明包装函数返回类型。

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

#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;
}

我认为代码应该工作,除了???

谢谢你的任何想法

关心凯文

使用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别名:

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)...);
}

或者您可以使用返回类型扣除:

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;
}

您可以将decltype与C ++ 11自动尾随返回类型一起使用:

template<typename FUNCTION, typename... ARGS>
auto wrapper(FUNCTION&& func, ARGS&&... args) -> decltype(func(std::forward<ARGS>(args)...))

现场演示


C ++ 14中 ,只需:

template<typename FUNCTION, typename... ARGS>
decltype(auto) wrapper(FUNCTION&& func, ARGS&&... args)

现场演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM