In the 3 code snippets below, only the first one is accepted by the compiler, while the second and third aren't. I think all three cases are essentially doing the same thing: I am instantiating a variable of type "int(int,int)". Why it's okay to use int(int,int) instead of int(*)(int,int) in a template, when it doesn't work anywhere else?
First
#include<iostream>
#include<list>
#include<numeric>
using namespace std;
template<typename T>
T func(T first, T second)
{
return first+second;
}
int main()
{
list<int> l;
l.push_back(2);
l.push_front(1);
l.push_back(3);
l.push_back(4);
cout << accumulate<list<int>::iterator, int, typeof(func<int>)>(l.begin(),l.end(),0,func<int>);
return 0;
}
The source code for the accumulate function in numeric library:
template<typename _InputIterator, typename _Tp,
typename _BinaryOperation>
_Tp accumulate(_InputIterator __first, _InputIterator __last,
_Tp __init, _BinaryOperation __binary_op)
{
for ( ; __first != __last; ++__first)
__init = __binary_op(__init, *__first);
return __init;
Second
#include<iostream>
#include<list>
using namespace std;
template<typename T>
T func(T x, T y)
{
return x;
}
typedef int _BinaryOperation (int, int);
int main()
{
_BinaryOperation __binary_op = func<int>;
return 0;
}
Third
#include<iostream>
#include<list>
#include<numeric>
using namespace std;
template<typename T>
T func(T x, T y)
{
return x+y;
}
int main()
{
int (*pt)(int, int) = &(func<int>);
cout << (*pt)(2,2);
int func_(int, int) = func<int>; //error
return 0;
}