带有函数类型参数的c++模板语法
Syntax of C++ templates with function type parameters
我已经习惯了函数指针的这种语法
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
与对应的函数指针的类型相同。很容易想象实现。
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_name
和pointer_name2
的类型相同:指向返回int
的函数,并接受两个类型为float
和char*
的参数。注意,这与int
等其他类型完全相同,不同之处在于不能将变量声明为函数类型,只能将指针指向函数。
std::function
(或boost::function
)的接口只取函数的签名。type参数不是指向函数的指针,而是函数的类型(如上面代码中的my_function_type
)
函数类型在c++ 11中不是新的(参见c++ 98中的8.3.5)。与TR1和boost为function
提供的功能相比,IIRC的改进非常小。
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 助记符和指向成员语法的指针
- 有人能分解一下这个c++模板的语法吗
- C++避免重复声明的语法是什么
- QMetaObject invokeMethod的基于函数指针的语法
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 单独定义模板化嵌套类方法的正确语法
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- 错误 C2760:语法错误:映射迭代器上意外的标记"标识符",预期的";"
- 为什么我会收到错误 C2143 语法错误:缺少"*"之前的';'?
- 奇怪的代码抛出编译错误模板< J,int aSize=10> C2143:语法错误:在"<"之前缺少";"
- 使用基类指针调用基类的值构造函数的语法是什么?
- 很好的语法来获取对向量/数组数据的大小引用?
- C++语法运算符功能?
- C++使用 rand 定义函数语法
- 什么文件可以修改 atom 的C++语法?
- 创建模板嵌套类实例的语法?
- C++语法差异:二维和一维数组(指针算术)
- 将信息输入到下面显示的结构向量中的正确语法/格式是什么