如何避免模板函数调用的歧义?

4

我不能理解来自于《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;
}  
1个回答

6

函数模板 foo 有两种重载形式。 foo<int> 可以是 foo<int>( int )(第一种) 或者 foo<int>( int* ) (第二种)。

为了消除歧义,你可以将其转换为相关的函数类型。

例如:

apply( static_cast<void(*)(int)>( &foo<int> ), 7 );

免责声明:这段代码甚至没有被编译器远程查看。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接