简体   繁体   English

使用std :: invoke调用模板化函数

[英]Using std::invoke to call templated function

I'm trying to call a templated member function using std::invoke as in the code snipped below. 我正在尝试使用std::invoke模板化成员函数,如下面的代码所示。

#include <functional>
#include <iostream>

struct Node
{
    template <typename T>
    T eval(T lhs, T rhs) { return lhs + rhs; }
};

int main(void)
{
    std::cout << std::invoke(&Node::eval<int>, 1, 2);

    return 0;
}

gcc 8.1 is giving me the error GCC 8.1给我错误

no matching function for call to 'invoke(unresolved overloaded function type, int, int)' 没有匹配的函数可调用“ invoke(未解析的重载函数类型,int,int)”

which I think it means that the function template is not actually instantiated. 我认为这意味着功能模板实际上并未实例化。

What am I missing to make the call possible? 我错过了什么才能打通电话?

The problem is that you try to call a member function with no objects. 问题是您尝试不带对象地调用成员函数。 There are two solutions: 有两种解决方案:

  1. Mark eval as static . eval标记为static
  2. Create a Node object and std::invoke the eval method on that object. 创建一个Node对象,然后在该对象上std::invoke eval方法。 It would look like this: 它看起来像这样:

     int main() { Node n{}; std::cout << std::invoke(&Node::eval<int>, n, 1, 2); return 0; } 

Here, the n object is passed as a object for this pointer to eval method. 在此,将n对象作为this指针的对象传递给eval方法。

Two problems: 两个问题:

First, your function template takes one type parameter, not two. 首先,您的功能模板采用一个类型参数,而不是两个。
Second, your function is not static , hence you can't use it without an object. 其次,您的函数不是static ,因此没有对象就无法使用它。

struct Node
{
    template <typename T>
    static T eval(T lhs, T rhs) { return lhs + rhs; }
    ^^^^^^
};

int main(void)
{
    std::cout << std::invoke(&Node::eval<int>, 1, 2);
                                         ^^^
    return 0;
}

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

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