带有函数类型参数的c++模板语法



我已经习惯了函数指针的这种语法

int (*pointer_name) (float, char *);
void call_function (void (*)(int), int);

在一些c++ 03函数库中,我看到这样使用类型:

abc::function<void(*)(int,float)> f;

在c++ 11的std::function中,我看到这样给出的类型

std::function<void(int,float)> f;

缺少一个(*)。为什么?

c++ 03 function<T>T与对应的函数指针的类型相同。很容易想象实现。

核心语言增强支持c++ 11中的

std::function。模板参数类型是否被扩展以适应可调用性?

std::function(以及它的灵感,boost::function)不仅存储函数指针。它还可以存储函数对象。从这个意义上讲,传递函数签名作为模板参数类似于智能指针通常将指针的类型作为模板参数,而不是指针类型!

对比:

int* p; // indirection to an object of type int
std::unique_ptr<int> q; // indirection to an object of type int

typedef void signature_type(); // a function type
// indirection to something callable with signature_type as a signature
// i.e. f() has type void
// only work for freestanding functions however
signature_type* f;
// indirection to something callable with signature_type as a signature
// i.e. g() has type void
// not restricted to function pointers!
std::function<signature_type> g;

这里没有什么神奇的,类型

void(int,float)

是没有名称的函数类型。它匹配像void g(int x, float y)这样的函数。

对于没有允许使用函数指针的模板,也可以使用函数类型

与其他元素一样,函数有一个类型,您可以在不同的上下文中使用该类型或指向该类型的指针。您期望的缺失的(*)只是指向语法的指针。

int (*pointer_name) (float, char *);
typedef int my_function_type(float,char*);
my_function_type * pointer_name2;

pointer_namepointer_name2的类型相同:指向返回int的函数,并接受两个类型为floatchar*的参数。注意,这与int等其他类型完全相同,不同之处在于不能将变量声明为函数类型,只能将指针指向函数

std::function(或boost::function)的接口只取函数的签名。type参数不是指向函数的指针,而是函数的类型(如上面代码中的my_function_type)

函数类型在c++ 11中不是新的(参见c++ 98中的8.3.5)。与TR1和boost为function提供的功能相比,IIRC的改进非常小。

最新更新