gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 22:23:57 24 4
gpt4 key购买 nike

我习惯于看到这样的函数指针语法

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 C++11 中的核心语言增强支持。是否扩展了模板参数类型以适应可调用性?

最佳答案

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

对比度:

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++ - 带有函数类型参数的 C++ 模板的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7245235/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com