Reflection in C++. How to pass a func as a parameter in c++

I am new to c++. So I'm trying to do something that is trivial but cannot figure out how.

I have a Class called Method:

class Method{

private:
    std::string nameMethod;
    Func f;

public:
    Method(std::string name,Func fun){
        nameMethod=name;
        f=fun;
    };

I want to create an Object of type Method called methDaniel which has

  1. string nameMethod = addDaniel.
  2. f = to a function that prints "Daniel".

How do I do this in the main.cpp file?

#include "Method.h"

using namespace std;

typedef void (*t_somefunc)();

void addDaniel(){
    cout<<"Daniel";
}


int main(){
    addDaniel();

    t_somefunc afunc = &addDaniel;
    Method* methDaniel = new Method("addDaniel",afunc);

}

Upvotes: 0

Views: 112

Answers (1)

R Sahu
R Sahu

Reputation: 206667

Move the typedef for defining t_somefunc to "Method.h".

Change the type of f from Fun to t_somefunc.

Method.h:

typedef void (*t_somefunc)();

class Method{

private:
    std::string nameMethod;
    t_somefunc f;

public:
    Method(std::string const& name, t_somefunc fun) : nameMethod(name), f(fun){}

Then, in main:

Method* methDaniel = new Method("addDaniel", addDaniel);

Upvotes: 2

Related Questions