Lambda表达式作为Visual C++ 2010中的CLR(.NET)委托/事件处理程序

abs*_*nce 11 .net events lambda delegates c++-cli

是否可以将Visual C++ 2010中的新lambda表达式用作CLR事件处理程序?我试过以下代码:

SomeEvent += gcnew EventHandler(
    [] (Object^ sender, EventArgs^ e) {
        // code here
    }
);
Run Code Online (Sandbox Code Playgroud)

它会导致以下错误消息:

错误C3364:'System :: EventHandler':委托构造函数的参数无效; 委托目标需要是指向成员函数的指针

我是在尝试不可能的,还是仅仅是我的语法错误?

Pav*_*aev 9

以下是我的解决方案,允许将lambdas(以及任何operator()可以调用的任何函数对象)包装到委托中.它有一些限制-具体地,它不支持与跟踪参考参数的代表(%在C++/CLI,ref/ out在C#); 并且它对委托可以采用的参数数量有一个上限(因为VC++ 2010不支持vararg模板) - 尽管可以通过简单的方式调整代码以支持尽可能多的代码.

#pragma once

#include <new>
#include <type_traits>

namespace detail
{
    struct return_type_helper
    {
    private:

        template<class D>
        struct dependent_false { enum { value = false }; };

        template <class D>
        struct illegal_delegate_type
        {
            static_assert(dependent_false<D>::value, "Delegates with more than 2 parameters, or with parameters of tracking reference types (T%), are not supported.");
        };

        struct anything
        {
            template<class T>
            operator T() const;
        };

    public:

        template<class D>
        static decltype(static_cast<D^>(nullptr)()) dummy(int(*)[1]);

        template<class D>
        static decltype(static_cast<D^>(nullptr)(anything())) dummy(int(*)[2]);

        template<class D>
        static decltype(static_cast<D^>(nullptr)(anything(), anything())) dummy(int(*)[3]);

        template <class D>
        static illegal_delegate_type<D> dummy(...);
    };


    template<class Func, class Aligner = char, bool Match = (std::tr1::alignment_of<Func>::value == std::tr1::alignment_of<Aligner>::value)>
    struct aligner
    {
        static_assert(Match, "Function object has unsupported alignment");
    };

    template<class Func, class Aligner>
    struct aligner<Func, Aligner, true>
    {
        typedef Aligner type;
    };

    template<class Func>
    struct aligner<Func, char, false> : aligner<Func, short>
    {
    };

    template<class Func>
    struct aligner<Func, short, false> : aligner<Func, int>
    {
    };

    template<class Func>
    struct aligner<Func, int, false> : aligner<Func, long>
    {
    };

    template<class Func>
    struct aligner<Func, long, false> : aligner<Func, long long>
    {
    };

    template<class Func>
    struct aligner<Func, long long, false> : aligner<Func, double>
    {
    };

    template<class Func>
    struct aligner<Func, double, false> : aligner<Func, void*>
    {
    };


    template<class F>
    ref class lambda_wrapper
    {
    public:

        lambda_wrapper(const F& f)
        {
            pin_ptr<F> pf = (interior_ptr<F>)&f_storage;
            new(pf) F(f);
        }

        ~lambda_wrapper()
        {
            pin_ptr<F> pf = (interior_ptr<F>)&f_storage;
            pf->~F();
        }

        template <class D>
        operator D^ ()
        {
            D^ d = nullptr;
            return gcnew D(this, &lambda_wrapper<F>::invoke<decltype(return_type_helper::dummy<D>(0))>);
        }

    private:

        template<class T>
        [System::Runtime::InteropServices::StructLayout(System::Runtime::InteropServices::LayoutKind::Sequential, Size = sizeof(T))]
        value struct embedded_storage
        {
        private:
            typename aligner<T>::type dummy;
        };


        embedded_storage<F> f_storage;

        template<class R>
        R invoke()
        {
            pin_ptr<F> pf = (interior_ptr<F>)&f_storage;
            return (*pf)();
        }

        template<class R, class A1>
        R invoke(A1 a1)
        {
            pin_ptr<F> pf = (interior_ptr<F>)&f_storage;
            return (*pf)(a1);
        }

        template<class R, class A1, class A2>
        R invoke(A1 a1, A2 a2)
        {
            pin_ptr<F> pf = (interior_ptr<F>)&f_storage;
            return (*pf)(a1, a2);
        }
    };
}

template<class F>
detail::lambda_wrapper<F>^ make_delegate(F f)
{
    return gcnew detail::lambda_wrapper<F>(f);
}
Run Code Online (Sandbox Code Playgroud)

样品用法:

Func<int, String^, int>^ f2 = make_delegate([&](int x, String^ y) -> int {
    Console::WriteLine("Func {0} {1}", x, y);
    return 2;
});
Run Code Online (Sandbox Code Playgroud)

虽然这在技术上你想要做什么,在实际应用中是比较有限的,由于事实上的C++ 0x lambda表达式被扩展到普通班,而不是refvalue的.由于普通类不能包含C++/CLI中的托管类型(即没有对象句柄类型的成员,没有跟踪引用类型的成员,也没有value class类型的成员),这意味着lambdas也无法捕获这些类型的任何变量.我没有找到跟踪引用的解决方法.对于value class,您可以使用非托管指针(pin_ptr如果需要),并捕获它.

对于对象句柄,您可以将它们存储gcroot<T>并捕获 - 但是存在严重的性能影响 - 在我的测试中,访问成员通过gcroot<T>比使用普通对象句柄慢大约40倍.对于单个调用来说,它实际上并不是绝对的衡量标准,但对于在循环中重复调用的东西 - 比如大多数LINQ算法 - 它将是一个杀手.但请注意,这仅适用于需要捕获lambda中的句柄的情况!如果你只是用它来编写谓词内联,或者更新一个计数器,它就可以正常工作.


Han*_*ant 7

没有办法,C++/CLI编译器没有得到更新以接受lambda语法.鉴于管理代码具有先机性,因此具有讽刺意味.