c++ c#委托等价

C++ C# delegate Equivalent

本文关键字:c++      更新时间:2023-10-16

我会尽量使这个问题简洁明了。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Something {
    static class Program {
        [STAThread]
        static void Main() {
            int blah = DoSomethingWithThis( delegate {
                Console.WriteLine( "Hello World" );
            } );
        }
        public static int DoSomethingWithThis( Action del ) {
            del.Invoke(); // Prints Hello World to the console
            int someArbitraryNumber = 31;
            return someArbitraryNumber;
        }
    }
}

在c#中,我可以使用匿名方法作为参数来做这样的事情;我想知道是否有人可以在c++中向我展示相同的东西,或者非常类似的东西,可以促进相同的结果。我打算用上面的代码为我的游戏在c++中创建一个DisplayList生成器。

例如

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
int main() 
{
    std::vector<std::string> v = { "Hello ", "Wordl" };
    std::for_each( v.begin(), v.end(), 
                   []( const std::string &s) { std::cout << s; } )( "n" );
    return 0;
}

输出为

Hello Wordl

所以你可以自己编写一个函数,接受一个函数对象(或std::function类型的对象)作为参数,然后传递一个lambda表达式作为参数。

例如

#include <iostream>
#include <string>
#include <functional>
int DoSomethingWithThis( std::function<void( void )> del )
{
    del();
    int someArbitraryNumber = 31;
    return someArbitraryNumber;
}

int main() 
{
    int blah = DoSomethingWithThis( [] { std::cout << "Hello World"; } );
    std::cout << "nblah = " << blah << std::endl; 
    return 0;
}

输出为

Hello World
blah = 31

在c#中你也可以用匿名方法代替lambda表达式

相关文章:
  • 没有找到相关文章