C++函数指针和模板

一、函数指针声明

//函数原型
double sum(double,double);
//函数指针的声明
double (*ptrSum)(double,double)

注意:
1,该语句声明了一个指针ptrSum,指向一个函数。
2,double *ptrSum(double,double) 不是函数指针 而是:声明一个函数,返回值为double *类型(指针函数)。
3,需要先定义函数,然后再定义函数指针。

//定义一个函数指针类型
typedef int (*FuncType)(int, int);	
using FuncType = int (*)(int, int);	//用using 定义别名
//定义一个普通函数
int Func(int a, int b)
{
	return a + b;
}
void TestFunc(int a, int b, FuncType p)	//p 就是函数指针 等价于int (*FuncType)(int, int);
{
	//通过函数指针调用函数
	cout << p(a, b) << endl;
}
int main()
{
	TestFunc(10, 25, Func);
	
	return 0;
}

二、用函数模板和函数指针结合

1. 函数指针形式

//定义一个函数指针类型
typedef int (*FuncType)(int, int);
//定义一个普通函数
int Func(int a, int b)
{
	return a + b;
}
//定义函数模板
template<typename T, typename F>
void TestFunc(const T& a, const T& b, F func)
{
	cout << func(a, b) << endl;
}
int main()
{
	TestFunc<int, FuncType>(25, 35, Func);	//TestFunc(25, 35, Func);也可以,编译器会自动推断类型
	return 0;
}

2. 可调用对象形式

class Test 
{
public:
	Test() { cout << "构造函数执行" << endl; }
	Test(const Test& test) { cout << "拷贝构造函数执行" << endl; }
	//重载圆括号
	int operator()(int a, int b) const
	{
		return a + b;
	}
};
int main()
{
	Test test;
	TestFunc<int, Test>(25, 35, test);	//可调用对象 会调用拷贝构造函数
	TestFunc<int, Test>(25, 35, Test());	//不会调用拷贝构造函数
	return 0;
}

三、默认模板参数

1. 类模板

类模板名后面必须用<>来提供额外信息。<>表示这是一个模板。

template<typename T = string, int size = 10>
class Array
{
public:
	void Func();
private:
	T arr[size];
};

template<typename T, int size>
void Array<T, size>::Func()
{
	cout << size << endl;
}

int main()
{
	Array<> a;	//完全使用模板缺省参数
	Array<int> b;	//指定一个模板参数类型
	return 0;
}

2. 函数模板

老标准只能为类模板提供默认模板参数,C++11标准可以为函数模板提供默认参数。

class Test
{
public:
	Test() { cout << "构造函数执行" << endl; }
	Test(const Test& test) { cout << "拷贝构造函数执行" << endl; }
	//重载圆括号
	int operator()(int a, int b) const
	{
		return a + b;
	}
};

template<typename T, typename F = Test>
//void TestFunc(const int& a, const int& b, Test func = Test())
void TestFunc(const T& a, const T& b, F func = Test())
{
	cout << func(a, b) << endl;
}

int main()
{
	TestFunc(15, 25);
	return 0;
}

注意:

  1. 同时给模板参数和函数参数提供缺省值。
  2. 注意写法 F func = Test()。
  3. Test重载圆括号。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值