我无法理解代码示例,取自"C++模板完整指南",8.3章.为什么编译器会说错误?作者说&foo <int>可能是两种不同的类型之一,为什么?
#include <iostream>
template <typename T>
void single(T x)
{
// do nothing
}
template <typename T>
void foo(T t)
{
std::cout << "Value" << std::endl;
}
template <typename T>
void foo(T* t)
{
std::cout << "Pointer" << std::endl;
}
template <typename Func, typename T>
void apply(Func func, T x)
{
func(x);
}
int main ()
{
apply(&foo<int>, 7);
int i = 0;
std::cin >> i;
}
Run Code Online (Sandbox Code Playgroud)
函数模板有两个重载foo.A foo<int>可以是foo<int>( int )(第一个)或foo<int>( int* )(第二个).
要解决歧义,您可以转换为相关的函数类型.
即
apply( static_cast<void(*)(int)>( &foo<int> ), 7 );
Run Code Online (Sandbox Code Playgroud)
免责声明:编码器甚至无法远程查看代码.