简体   繁体   中英

How to avoid ambiguous call of template function?

I cannot understand example of code, taken from "C++ Templates The Complete Guide", 8.3 chapter. Why does compiler say about error? Author says that &foo< int > could be one of two different types, why?

#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;
}  

There are two overloads of function template foo . A foo<int> could be either foo<int>( int ) (the first) or foo<int>( int* ) (the second).

To resolve the ambiguity you can cast to the relevant function type.

Ie

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

Disclaimer: code not even viewed at a distance by a compiler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM