我无法理解来自8.3章“C++模板完整指南”的代码示例。为什么编译器会提到错误?作者说&foo 可能是两种不同类型之一,为什么呢?
#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;
}
最佳答案
函数模板foo
有两个重载。 foo<int>
可以是foo<int>( int )
(第一个)或foo<int>( int* )
(第二个)。
要解决歧义性,可以将其强制转换为相关的函数类型。
即
apply( static_cast<void(*)(int)>( &foo<int> ), 7 );
免责声明:编译器甚至不会远距离查看代码。