如何在函数内部定义函子
how to define a functor inside a function
有时,我需要一些函数帮助器来操作列表。我尽量使作用域保持在局部。
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
struct Square
{
int operator()(int x)
{
return x*x;
}
};
int a[5] = {0, 1, 2, 3, 4};
int b[5];
transform(a, a+5, b, Square());
for(int i=0; i<5; i++)
cout<<a[i]<<" "<<b[i]<<endl;
}
hello.cpp: In function ‘int main()’:
hello.cpp:18:34: error: no matching function for call to ‘transform(int [5], int*, int [5], main()::Square)’
如果我把Square
从main()
中移出,就可以了
你不能这么做。然而,在某些情况下,您可以使用boost::bind
或boost::lambda
库来构建函数,而无需声明外部结构。此外,如果您有一个最新的编译器(如gcc版本4.5),您可以启用新的c++ 0x特性,允许您使用lambda表达式,允许这样的语法:
transform(a, a+5, b, [](int x) -> int { return x*x; });
在当前标准(c++ 98/03)中,局部类(局部函子)不能作为类用作模板形参。
正如这里的几个答案所指出的,c++在0x之前不能使用局部类型作为模板参数。为了避免这个问题(除了希望我所从事的项目将很快迁移到c++ 0x之外),我通常做的是将各自的局部类作为私有嵌套类放在需要这个函子的成员函数的类中。或者,我有时将函子放在各自的.cpp
文件中,认为这样更干净(并且编译速度更快)。
我认为对这个问题最好的回答是"使用函数式编程语言"。
相关文章:
- 如何理解c++中在命名空间内部定义的枚举类型enum
- 在模板类内部定义的枚举上的嵌套类的部分专用化
- 静态指针指向这个为mock for googletest定义的类内部
- 为什么在匿名名称空间中定义的模板时,为什么内部链接错误
- C++构造函数具有内部链接,但未定义 [-Wundefined-internal]
- 静态数组溢出堆栈(seg 错误 11)仅在类定义内部时,否则不会..?
- 使用包含该结构内部结构的 using 定义
- G++ 自定义任务在外部终端中打开,与 VS 代码内部终端
- 类定义内部"error: 'a' does not name a type"
- IFDEF块内部对功能的未定义引用
- 有符号整数溢出、内部函数和未定义的行为
- 是定义的函数参数的内部执行顺序
- 在哪里放置 PRIVATE 嵌套(内部)类的非成员函数定义
- 为什么SFINAE(enable_if)从类定义内部工作而不是从外部工作
- Sendmessage在方法定义内部无法正常工作
- 内联方法:类定义内部与外部类定义
- 常量静态成员初始化 - 类定义内部与外部类定义
- 在结构定义内部声明结构的堆栈
- 在C++中,在类定义内部或外部定义方法体是否更为传统
- 在类定义内部和外部定义成员函数之间有区别吗