如何在函数内定义函子 [英] how to define a functor inside a function

查看:217
本文介绍了如何在函数内定义函子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时,我需要一些functor-helper来操纵列表。我尽量保持范围尽可能本地化。

  #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 [i] < ; endl;
}






  hello.cpp:在函数'int main()':
hello.cpp:18:34:error:没有匹配的函数调用' 5],main():: Square)'



如果我移动 Square c> c>

$

>

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



transform(a,a + 5,b,[](int x) - > int {return x * x;});


Sometimes, I need some functor-helper to manipulate list. I try to keep the scope as local as possible.

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

If I move Square out of main(), it's ok.

解决方案

You cannot do it. However, in some cases, you can use boost::bind or boost::lambda libraries to build functors without declaring an outside structure. Also, if you have a recent compiler (such as gcc version 4.5) you can enable the new C++0x features which allow you to use lambda expressions, allowing such syntax:

transform(a, a+5, b, [](int x) -> int { return x*x; });

这篇关于如何在函数内定义函子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆