gpt4 book ai didi

c++ - 将函数传递给可变函数模板

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:06:44 27 4
gpt4 key购买 nike

考虑以下函数模板:

template<typename RetType, typename... ArgTypes>
void foo0(std::function<RetType(ArgTypes...)> f) {}

template<typename RetType, typename ArgType>
void foo1(std::function<RetType(ArgType)> f) {}

以及以下函数:

void bar(int n) {}

为什么会出现以下情况:

 foo0<void, int>(bar);  // does not compile
foo1<void, int>(bar); // compiles fine

编译错误是(gcc-8 with C++17):

error: no matching function for call to 'foo0<void, int>(void (&)(int))'
foo0<void, int>(bar);
^
note: candidate: 'template<class RetType, class ... ArgTypes> void foo0(std::function<_Res(_ArgTypes ...)>)'
void foo0(std::function<RetType(ArgTypes...)> f) {}
^~~~
note: template argument deduction/substitution failed:
note: mismatched types 'std::function<void(_ArgTypes ...)>' and 'void (*)(int)'
foo0<void, int>(bar);

使用虚拟模板

template<typename T>
void bar(int n) {}

制造 foo0<void, int>(bar<int>);在 gcc-8 中编译正常,但在 Apple LLVM 版本 10.0.0 (clang-1000.11.45.5) 中使用 clang 时出错。

clang错误是

error: no matching function for call to 'foo0'
foo0<void, int>(bar<int>);
^~~~~~~~~~~~~~~
note: candidate template ignored: could not match 'function<void (int, type-parameter-0-1...)>' against 'void (*)(int)'
void foo0(std::function<RetType(ArgTypes...)> f) {}

最佳答案

Why does the following occur [?]

调用时考虑一下

 foo0<void, int>(bar); // compilation error
foo1<void, int>(bar); // compile

foo0()foo1()期待 std::functionbar是指向可以转换为 std::function 的函数的指针但不是std::function .

foo1()情况下,你明确了 RetTypeArgType模板参数,因此编译器可以转换 barstd::function<void(int)>一切顺利。

但是 foo0()大小写不同,因为模板参数 ArgTypes...是一个可变的,调用 foo0<void, int>(bar)你没有明确完整的 ArgTypes...可变列表,但只有第一种类型。

如果我没记错的话,问题是编译器试图推导出 ArgTypes... 的其余部分来自 bar参数但是bar不是 std::function所以编译器无法推断出 ArgTypes... 的其余部分, 所以错误。

我想

foo0<void, int>(std::function<void(int)>{bar});

或者只是

foo0(std::function<void(int)>{bar});

或者(仅限 C++17)

foo0(std::function{bar});

应该编译因为调用foo0()这样,函数接收到 std::function。因此编译器可以完全推导出模板参数。

我不明白 bar() 的版本如何使用虚拟模板参数

foo0<void, int>(bar<int>);

可以用 g++-8 编译,我想这是一个 g++ 错误。

关于c++ - 将函数传递给可变函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54509295/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com