Reputation: 4512
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;
}
Upvotes: 4
Views: 342
Reputation: 145204
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.
I.e.
apply( static_cast<void(*)(int)>( &foo<int> ), 7 );
Disclaimer: code not even viewed at a distance by a compiler.
Upvotes: 6