注意:这篇文章上次更新于1416天前,文章内容可能已经过时。
This article was last updated1416 days ago, the content may be outdated.
本文记录一下 function 函数对象的实现过程。
function 对象实际上就是对函数指针的封装,比如有如下一个函数
This article documents the implementation process of the function function object.
The function object is actually a wrapper around a function pointer. For example, given the following function
1 | void hello(std::string& str) |
在主函数中这样使用 function 对象。
In the main function, the function object is used like this.
1 | int main() |
针对这种使用方法,写出对应的类模板。
For this usage, write the corresponding class template.
1 | // 声明一个类模板 |
如果传入的函数是下面这样的
If the function passed in is like the following
1 | int add(int a,int b) |
写出对应的特化版本也很简单。
Writing the corresponding specialization is also simple.
1 | template<typename R,typename A1,typename A2> |
写到这里,想必大家都想到了一个问题,就是函数指针的类型是无穷的,没办法写出无穷个特例化版本。
对这个问题进行简单的抽象,一个函数指针其实就是包括 返回值类型 和 参数列表。上面的两个特例化版本中唯一的不同也就是形参列表的不同。 C++11 的可变模板参数提供了解决方案。
At this point, everyone has probably thought of a problem: the types of function pointers are infinite, so it is impossible to write an infinite number of specializations.
To abstract this problem simply, a function pointer actually consists of the return type and the parameter list. The only difference between the two specializations above is the parameter list. C++11’s variadic template parameters provide the solution.
1 | // 返回值类型 R, 可变参数类型 A |


