Templates and fuction pointer

I'm trying a generic function which if say to me that it is smallar or it is bigger.

For example:
foo(5,30,comp); Should return false
foo(z,b,comp); Should return true

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template <typename A, typename B>
bool comp()(const A& lhs, const B& rhs)
{
	return lhs > rhs;
}
template <typename A, typename B>
bool f(A a, B b, bool (*foo)(A,B))
{
	return foo(a, b);
}
int main()
{
	std::cout << std::boolalpha;
	std::cout << f(5, 20,comp<int, int>) << '\n';
        std::cout << f('z', 'c',comp<char, char>) << '\n';
}


Compiler is saying that:
1
2
Severity	Code	Description	Project	File	Line	Suppression State
Error	C2784	'bool f(A,B,bool (__cdecl *)(A,B))': could not deduce template argument for 'bool (__cdecl *)(A,B)' from 'overloaded-function'



yes its true, I know my mistake but I don't know how can I solve it?
Last edited on
First, for this particular task, you are overcomplicating.
1
2
3
4
5
6
7
8
#include <iostream>

int main()
{
  std::cout << std::boolalpha;
  std::cout << (20 < 5) << '\n';
  std::cout << ('c' < 'z') << '\n';
}


Second, a different compiler can point out different things, for example your line 2 has too many parentheses.

Function pointer typedef (pre C++11) can't be templated directly but indirectly through a struct, alternatively try the using keyword of C++11 (commented out in below code):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>

template <typename T>
bool comp(const T& lhs, const T& rhs)
{
	return lhs > rhs;
}
template <typename T>
struct foo
{
    typedef bool(*type)(const T& lhs, const T& rhs);
};
//using foo = bool (*)(const T& lhs, const T& rhs);

int main()
{
    foo<const char&>::type foo = comp;
   // foo<const char&> foo = comp;

}
Try these?

http://en.cppreference.com/w/cpp/utility/functional/greater
http://en.cppreference.com/w/cpp/utility/functional/less

Probably a good idea to define operator< or operator> for types other than the built in ones.
Topic archived. No new replies allowed.