Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/132.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在函数中定义函子_C++ - Fatal编程技术网

C++ 如何在函数中定义函子

C++ 如何在函数中定义函子,c++,C++,有时,我需要一些函子助手来操作列表。我尽可能地保持范围的局部性 #include <iostream> #include <algorithm> using namespace std; int main() { struct Square { int operator()(int x) { return x*x; } }; int a[5] = {0, 1, 2,

有时,我需要一些函子助手来操作列表。我尽可能地保持范围的局部性

#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;
}

如果我将
Square
移出
main()
,就可以了。

您不能这样做。但是,在某些情况下,您可以使用
boost::bind
boost::lambda
库来构建functor,而无需声明外部结构。此外,如果您有最新的编译器(如gcc版本4.5),则可以启用新的C++0x功能,允许您使用lambda表达式,允许使用以下语法:


transform(a,a+5,b,[](intx)->int{returnx*x;}) < /P> < P>在当前标准(C++ 98/03)中,局部类(局部函子)不能作为模板参数使用。

< P>我认为这个问题的最佳答案是“使用编程语言”。C++/P>0P>正如这里的几个答案指出的,C++ P0X不能使用局部类型作为模板参数。为了避免这个问题,我通常做的事情(除了希望我所从事的项目很快会转移到C++0x之外)是将相应的本地类作为私有嵌套类放在需要这个函子的成员函数的类中。或者,我有时会将函子放在相应的
.cpp
文件中,想象它更干净(编译速度略快)。

.Hmm。。。我从问题中复制了代码,并在VS2010上进行了尝试,效果很好…:-\。标签是问题的一部分,所以虽然这是一个与这个问题有点类似的问题的答案,但我不认为这是这个问题的答案。
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)’