spr*_*aff 15 c++ templates c++11 std-function
我习惯于在函数指针中看到这样的语法
int (*pointer_name) (float, char *);
void call_function (void (*)(int), int);
Run Code Online (Sandbox Code Playgroud)
在一些C++ 03函数库中,我看到以这种方式使用的类型:
abc::function<void(*)(int,float)> f;
Run Code Online (Sandbox Code Playgroud)
在C++ 11中,std::function我看到了这种方式给出的类型
std::function<void(int,float)> f;
Run Code Online (Sandbox Code Playgroud)
有一个失踪(*).为什么?
在C++ 03 function<T>已经T是相同的类型到相应的函数指针.很容易想象实现.
std::function在C++ 11中,核心语言增强功能支持它.是否已扩展模板参数类型以适应可调用性?
Luc*_*ton 17
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
Run Code Online (Sandbox Code Playgroud)
同
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;
Run Code Online (Sandbox Code Playgroud)
这是一个有用的约定.
这里没有什么神奇的类型
void(int,float)
Run Code Online (Sandbox Code Playgroud)
是没有名称的函数的类型.它匹配像这样的功能void g(int x, float y).
有了模板,你不具备使用函数指针,你可以使用函数类型为好.
与其他元素一样,函数具有类型,您可以在不同的上下文中使用类型或指向该类型的指针.(*)您期望的缺失只是指向语法的指针.
int (*pointer_name) (float, char *);
typedef int my_function_type(float,char*);
my_function_type * pointer_name2;
Run Code Online (Sandbox Code Playgroud)
类型pointer_name和pointer_name2是相同的:指向函数的指针,该函数返回int并接受类型float和的两个参数char*.请注意,这与其他类型完全等效int,区别在于您不能将变量声明为类型函数,只是指向函数的指针.
std::function(或boost::function)的接口只是获取函数的签名.type参数不是指向函数的指针,而是函数的类型(如my_function_type上面的代码中所示)
| 归档时间: |
|
| 查看次数: |
3360 次 |
| 最近记录: |