Visual C++ - anonymous methods

耗尽温柔 提交于 2020-01-04 03:59:09

问题


Hi Is there any way to use anonymous methods in Visual C++ ??


回答1:


Visual C++ 2010 supports C++0x lambda expressions,(1) which can be used as anonymous functions:

int i = ([](int x) { return 40 + x; })(2); // i = 42

(1) It's more correct to say that Visual C++ 2010 supports one of the draft specifications for C++0x lambda expressions; several relatively minor changes have been made to that draft specification since Visual C++ 2010 was released.




回答2:


As others have stated, C++0x will support lambdas. In the meantime, you can use Boost Lambda.




回答3:


If you can't use C++0x like everyone else has suggested there are a number of ways around what you're attempting to do which mimic to some degree but do not completely capture the anonymous aspect:

template<typename T>
void foo(const T& _someFunctor, double _someArgument){
    _someFunctor(_someArgument);
}

Or you could have a better defined structure as:

int bar(const boost::function<int(double,double)>& _aFunction, double arg1, double arg2){
    return _aFunction(arg1+2.0, arg2+2.0);
}

the Boost::Function approach is probably the most lient as it defines a very strict function interface while allowing use with:

  1. Boost::Bind
  2. functions
  3. member functions
  4. functors (function like objects)



回答4:


I assume you mean C++/CLI, anonymous methods is a C# term. No, not supported. It doesn't support the C++0x lambdas either.




回答5:


Yes, C++0x allows lambda functions.



来源:https://stackoverflow.com/questions/4855153/visual-c-anonymous-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!