读书人

C++中施用模板传递函数类型

发布时间: 2012-11-14 10:12:19 作者: rapoo

C++中使用模板传递函数类型

首先看了常用的写法:

template<typename T>class C{public:C(T _t){_t('a');//ok(*_t)('a');//okT *t1=_t;//okt1=_t;//(*t1)=_t;//compile error!assignment of read-only location//T t2=_t;//compile error!variable 't2' has function type}};int fi(char){return 1;}int main(){C<int(char)> c(fi);//使用模板传递函数类型return 0;}


int(char)是使用模板传递函数类型,c(fi)给C的构造函数传递函数指针fi,对fi的调用,可以使用_t('a')和(*_t)('a')两种方式(当然,你也可以在main函数中使用fi('a')和(*fi)('a')调用函数fi),但是对于int(char)类型的变量t2,却无法复制构造,只能使用指针赋值方式。

在对int(char)函数类型变量赋值时,它表现得像是一个函数常量(就像函数名f1一样),而如果对其指针的引用赋值时,它表现得像typedef int(*const constPF)(char)一样。所以,它更像是一个“constructor、copy constructor和operator=”都为private的class,即无法创建它的实例、无法对它的实例初始化或赋值。只能对它的指针进行初始化和赋值然后使用。


读书人网 >C++

热点推荐