考虑以下函数模板:
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) {}
在gcc-8中,foo0<void, int>(bar<int>);
可以编译通过,但是在使用Apple LLVM version 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) {}
std::function
的类型几乎总是错误的。你真正想要解决的问题是什么? - Barry