简体   繁体   English

从 std::function 推导出模板参数

[英]Deducing template parameters from std::function

I'm writing a little class using a static template member function trying to map a std::function with its parameters :我正在使用静态模板成员函数编写一个小类,尝试将 std::function 与其参数映射:

class test
{
public:
    template <typename R, typename... Args>
    static double exec(std::function<R(Args...)> func, Args && ... args) {
        func(std::forward<Args>(args)...);
        // do something
        return 0.0;
    }
};

Supposing I have these trivial functions :假设我有这些微不足道的功能:

  • void f1() { ; }
  • int f2(int v) { return v; }
  • double f3(int v1, float v2) { return (double)v1 * (double)v2; }

I would like to call my test::exec function like this :我想像这样调用我的test::exec函数:

test::exec(f1);
test::exec(f2, 4);
test::exec(f3, 1, 3.14f);

I'm using Visual Studio and I get this error for the second case (f2) :我正在使用 Visual Studio,但在第二种情况 (f2) 中出现此错误:

error C2672: 'test::exec': no matching overloaded function found
error C2784: 'double test::exec(std::function<_Ret(_Types...)>,Args &&...)': could not deduce template argument for 'std::function<_Ret(_Types...)>' from 'int (__cdecl *)(int)'

Nevertheless, it work if I specify the the types in the template signature : test::exec<int, int>(sq, 4);尽管如此,如果我在模板签名中指定类型,它会起作用: test::exec<int, int>(sq, 4); Obviously, I would like to avoid that.显然,我想避免这种情况。 Also, I don't know how to formulate the call to f1 with this syntax.另外,我不知道如何使用此语法制定对 f1 的调用。

Is it possible to achieve this goal without specifying the signature of the template parameters?是否可以在不指定模板参数签名的情况下实现此目标?

The compiler can't deduce the std:function arguments and return type, because you are not passing exec a std::function at all.编译器无法推导出std:function参数和返回类型,因为您根本没有传递exec一个std::function


Instead of a std::function , you can just make exec accept an arbitrary type of callable (which includes functions), and let the compiler deduce its signature:代替std::function ,您可以让exec接受任意类型的可调用(包括函数),并让编译器推断其签名:

template <typename Func, typename... Args>
static double exec(Func func, Args && ... args);

If you do need to know the return type of the function that you pass to exec , you can do it like this:如果您确实需要知道传递给exec的函数的返回类型,您可以这样做:

template <typename Func, typename... Args>
static double exec(Func func, Args && ... args) 
{
  using R = decltype(func(args...));
  // ...
}

The answer is adapted from @IgorTandetnik's comments.答案改编自@IgorTandetnik 的评论。

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

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