Suraksha Ajith
Suraksha Ajith

Reputation: 892

Delegates usage in C++/CLI

I'm trying to use Delegate in C++/Cli, I referred this video which is in C#

#include <iostream>
#include"stdafx.h"

using namespace System;
using namespace System::Collections::Generic;


public ref class Employee
{
public:
    Employee() {};
    ~Employee() {};
public:
    int ID;
    String ^name;
    int Salary;
    int Experience;

public: static void Promote(List<Employee^>^ members,promoteDelegate^ promo)
{
    for each (Employee ^emp in members)
    {
        if(promo(emp))
        Console::WriteLine("{0} is Promoted", emp->name);
    }
}

};

delegate bool promoteDelegate(Employee^ emp);

ref class MyClass
{
public:
    MyClass() {};
    ~MyClass() {};

static bool func(Employee^ emp)
{
    return (emp->Salary >= 5000);
}

int main(array<System::String ^> ^args)
{
    List<Employee^> ^Employee_List = gcnew List<Employee^>;
    Employee^ emp1 = gcnew Employee;
    emp1->name = "Ajanth"; emp1->ID = 0;emp1->Salary = 50000;emp1->Experience = 3;

    Employee^ emp2 = gcnew Employee;
    emp2->name = "Aman"; emp2->ID = 1;emp2->Salary = 45000;emp2->Experience = 9;

    Employee^ emp3 = gcnew Employee;
    emp3->name = "Ashish"; emp3->ID = 2;emp3->Salary = 60000;emp3->Experience = 4;

    Employee_List->Add(emp1);
    Employee_List->Add(emp2);
    Employee_List->Add(emp3);

    promoteDelegate ^promoDel = gcnew promoteDelegate(func);

    Employee::Promote(Employee_List, promoDel); //Error here
    return 0;
}
};

I'm getting compiler error as below

'Employee::Promote' does not take 2 arguments. function "Employee::Promote" cannot be called with the given argument list.
argument types are: (System::Collections::Generic::List ^, promoteDelegate ^

Upvotes: 1

Views: 331

Answers (1)

Hans Passant
Hans Passant

Reputation: 941257

Always start from the top of the error list. Later messages get increasingly less reliable. First error you'll get is for the Promote() function definition, the compiler does not yet know what promoteDelegate means. Which then causes more errors, like the one you quoted.

Important rule to keep in mind is that, very unlike C#, the C++ compiler uses single-pass compilation. All types must be declared before they are used. That can be pretty awkward, like it is here, since the delegate type itself uses the Employee type. A chicken-and-egg problem that must be solved with a forward declaration:

ref class Employee;    // Forward declaration
public delegate bool promoteDelegate(Employee^ emp);

public ref class Employee
{
   // etc..
}

Fix your #includes as well, stdafx.h must always be included first.

Upvotes: 2

Related Questions