5

I'm trying to create an array of functors at compile time, like so: (complete file):

#include <functional>
using namespace std;

function< float( float tElevation, float pAzimuth )> colorFunctions[] = {
  []( float tElevation, float pAzimuth ) -> float {
    return 2.0f ;
  },
} ;

int main()
{
}

That works fine. But as soon as you try to create a local inside the functor block, like this:

function< float( float tElevation, float pAzimuth )> colorFunctions[] = {
  []( float tElevation, float pAzimuth ) -> float {
    float v = 2.0f ;
    return v ;
  },
} ;

You get Error 1 error C1506: unrecoverable block scoping error

How can I declare locals inside these blocks? It doesn't seem to work.

4

2 回答 2

0

我可以在 MSVC 2010,SP1 上重现这一点。VS10 因 lambdas 和作用域的一些问题而闻名。我已经尝试了很多,但没有发现任何漂亮的东西。丑陋,丑陋的解决方法会产生一些初始化开销,但可以按预期工作:

#include <functional>
#include <boost/assign/list_of.hpp>
#include <vector>
using namespace std;

typedef function< float( float tElevation, float pAzimuth )> f3Func;
vector<f3Func const> const colorFunctions = boost::assign::list_of(
  f3Func([]( float /*tElevation*/, float /*pAzimuth*/ ) -> float {
    float v = 2.0f ;
    return v ;
  }))
  ([](float a, float b) -> float {
    float someFloat = 3.14f;
    return a*b*someFloat;
  })
;

#include <iostream>

int main()
{
  cout << colorFunctions[1](0.3f,0.4f) << '\n';
}
于 2012-11-21T10:17:07.113 回答
-1

我在 ubuntu 12.04 上使用以下行编译了以下代码:
g++-4.7 -std=c++0x main.cpp
它工作正常。您使用的是什么平台和什么编译器?

#include <iostream>
#include <functional>

using namespace std;

function<float (float,float)> funcs[] = {
    [] (float a, float b) -> float {
        float c = 2.0f;
        return c;
    }
};

int main() {
    std::cout << funcs[0](1,2) << std::endl;
}
于 2012-08-11T14:59:22.043 回答