函数指针及其typedef

 实际用处还是通用型编程?

 #include <iostream>

using namespace std;

typedef bool (*COMPARE)(int a, int b);

bool greater_than(int a, int b)
{
	return a > b;
}

bool lesser_than(int a, int b)
{
	return a < b;
}

bool equal(int a, int b)
{
	return a == b;
}

bool compare(int a, int b, COMPARE cmp)
{
	return cmp(a, b);
}

int main()
{
	int a = 5;
	int b = 6;

	cout << "a = " << a << endl;
	cout << "b = " << b << endl;

	cout << endl;

	cout << "a > b is " << compare(a, b, &greater_than) << endl;
	cout << "a < b is " << compare(a, b, &lesser_than) << endl;
	cout << "a = b is " << compare(a, b, &equal) << endl;

	cout << endl;

	COMPARE compare_group[] = {&greater_than, &lesser_than, &equal};
	COMPARE* which = compare_group;

	cout << "a > b is " << compare(a, b, which[0]) << endl;
	cout << "a < b is " << compare(a, b, which[1]) << endl;
	cout << "a = b is " << compare(a, b, which[2]) << endl;
}

你可能感兴趣的:(函数指针,typedef)