【问题标题】:std::invoke does not like variadic template member functions?std::invoke 不喜欢可变参数模板成员函数?
【发布时间】:2021-11-18 01:14:00
【问题描述】:

我正在尝试使用std::invoke()std::apply() 调用可变参数函数模板。

我提前道歉,因为我基本上是在这里丢了一段代码,并请人帮助我理解错误消息以解决问题。

所以,在下面的示例代码中,

  • std::invoke() 在非可变模板函数上工作正常。
  • std::invoke() 上的可变参数模板函数无法编译!
#include <functional>
#include <tuple>

struct Thing
{
    // Some simple functions to test things out
    int func0() { return 0; }
    int func1(int) { return 1; }
    int func2(int, int) { return 2; }

    // A variadic template function that causes problems below
    template<typename ...Args>
    int funcn(Args&&...) { return 99; }
};

int main()
{
    Thing thing;

    // These work fine
    std::invoke(&Thing::func0, thing);
    std::invoke(&Thing::func1, thing, 1);
    std::invoke(&Thing::func2, thing, 1, 2);

    // This one doesn't work
    std::invoke(
        &Thing::funcn, 
        thing, 
        1, 2, 3, 4
    );
}

我得到的错误在这里:(x86-64 clang 12.0.1(编译器#1)的输出)

 Wrap lines
<source>:26:5: error: no matching function for call to 'invoke'
    std::invoke(
    ^~~~~~~~~~~
functional:94:5: note: candidate template ignored: couldn't infer template argument '_Callable'
    invoke(_Callable&& __fn, _Args&&... __args)
    ^

【问题讨论】:

  • &amp;Thing::funcn 尝试获取函数的地址,但由于它是一个模板,它没有可以解析到的单个地址。您要么需要指定参数,将其转换为正确的类型,要么将其包装在 lambda 中。

标签: c++ templates c++17 variadic-templates std-invoke


【解决方案1】:

std::invoke 需要一个可调用函数。 funcn 是一个函数模板,你需要实例化它才能得到一个真正的函数,然后你就可以得到它的地址。

这意味着(明确地)向函数提供模板参数,您希望如何实例化它,以便std::invoke 可以看到它可以调用的函数。

std::invoke(
    &Thing::funcn<int, int, int, int>, // works now
    thing,
    1, 2, 3, 4
);

【讨论】:

  • 成功了!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-15
  • 2019-01-18
  • 2019-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多