MarkShep

I'm getting an annoying error when trying to use a delegate. It works in one place but not in another. In a console application I have the following code:

Code Snippet

// TestWaitCallback.cpp : main project file.

#include "stdafx.h"

#include "TestClass.h"

using namespace System;

using namespace System::Threading;

void MyFunction(System::Object^)

{

}

int main(array ^args)

{

ThreadPool::QueueUserWorkItem(gcnew WaitCallback(&MyFunction));

return 0;

}

This compiles OK. However, in the same project I have a class defined as follows:

Code Snippet

#pragma once

using namespace System::Threading;

public ref class TestClass

{

public:

TestClass(void) {

}

void RunTestFunction() {

ThreadPool::QueueUserWorkItem(gcnew WaitCallback(&TestClass::TestFunction));

}

void TestFunction(System::Object^) {

}

};

This fails with the following error:

Code Snippet
error C3352: 'void TestClass::TestFunction(System::Object ^)' : the specified function does not match the delegate type 'void (System::Object ^)'

It certainly looks to me as though the function does match the delegate (and in the 1st code sample it's exactly the same and it compiles).

Can anyone see what I'm doing wrong



Re: Visual C++ Express Edition Delegate Error

eperales

Wild guess: The second function is a member of a class, and the C++ compiler will add a hidden first parameter to pass the this pointer, making the signature indeed different.

Does it work if you make TestClass::TestFunction static (thus getting rid of the extra parameter)




Re: Visual C++ Express Edition Delegate Error

nobugz

You're calling a member method, you need to pass the class instance reference. Write it like this:

void RunTestFunction() {
ThreadPool:: QueueUserWorkItem(gcnew WaitCallback(this, &TestClass:: TestFunction));
}






Re: Visual C++ Express Edition Delegate Error

MarkShep

Thanks nobugz. That worked perfectly.