如何在函数内部定义函子

how to define a functor inside a function

本文关键字:定义 内部 函数      更新时间:2023-10-16

有时,我需要一些函数帮助器来操作列表。我尽量使作用域保持在局部。

#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)’

如果我把Squaremain()中移出,就可以了

你不能这么做。然而,在某些情况下,您可以使用boost::bindboost::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文件中,认为这样更干净(并且编译速度更快)。

我认为对这个问题最好的回答是"使用函数式编程语言"。