编译器在不知道 foo 函数模板参数 T 的类型时,是如何决定调用 bar 函数的呢?
通常情况下,当我们调用 foo(2)
时,通过参数 2
推断出 T
的类型是 int
。
而在这里,T
是根据函数 bar 的参数来推导的,而 foo 函数则将其作为参数传递给了 bar 函数。
#include <iostream>
template<typename T>
void foo(const T& a_) {
std::cout << a_<< std::endl;
}
void bar(void (*ptr) (const int&)) {
std::cout << "bar called" << std::endl;
}
int main() {
bar(foo);
}
编译器: gcc
void (*ptr) (const int&) = foo;
一样工作。 - apple appleauto* p = static_cast<void (*) (const int&)>(foo);
- apple applebar
接受一个函数指针ptr
作为参数,而int版本的bar
可以匹配它。 - nick