How do I forward declare a delegate in C++/CLI?

2019-03-02 10:49发布

问题:

How?

The following did not work:

delegate MyDelegate;
ref class MyDelegate;
delegate void MyDelegate;

The following works for declaration:

public delegate void MyDelegate(Object ^sender, MyArgs ^args);

But using it as a forward declaration gives me

error C3756: 'MyNameSpace::MyDelegate': delegate definition conflicts with an existing symbol

回答1:

This work's for me;

stdafx.h:

public delegate void Handler(bool isit);

cli1.cpp:

#include "stdafx.h"
using namespace System;

namespace MY {
   namespace Namespace
   {
       public ref class Objeks
       {
           public: Objeks() {}
           public: event Handler^ OnHandler;
           public: void __clrcall Runner(bool checkit)
           {
              if(&Objeks::OnHandler != nullptr) 
                OnHandler(checkit);
           }
       };
   }
}

I left the default VS 2010 C++/CLI project alone for the most part, I would expect that if your going through the trouble of forward declarations, the using namespace System; would go in the header's also :)

Maybe you did not want to use event? But it seems to simply the structure.

I added the error check after considering (Error Compiling C++/CLI Delegate call using Predicate with Array::FindAll()).