具有函数类型参数的C ++模板的语法 [英] Syntax of C++ templates with function type parameters

查看:102
本文介绍了具有函数类型参数的C ++模板的语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯看到函数指针的语法。

I'm used to seeing syntax like this for function pointers

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

在一些C ++ 03函数库中,我看到类型使用这种方式:

In some C++03 functional libraries I see types used this way:

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

在C ++ 11的std :: function中我看到这种类型的

In C++11's std::function I see the type given this way

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

缺少(*)。为什么?

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

The C++03 function<T> has T being an identical type to the corresponding function pointer. It's easy to imagine the implementation.

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

std::function in C++11 is supported by core language enhancements. Have template argument types been extended to accomodate callability?

推荐答案

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

std::function (and its inspiration, boost::function) does not only store function pointers. It can also store function objects. In that sense, passing a function signature as a template parameter is similar to how a smart pointer usually take the type of the pointee as a template parameter, not a pointer type!

对比度:

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;

这是一个有用的约定。

这篇关于具有函数类型参数的C ++模板的语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆