Salvolannister
Salvolannister

Reputation: 33

How to make a list of functions in C++?

I want to make a list of function, but the push_back doesn't work, can someone tell me why?

#include "stdafx.h"
#include <string>
#include <iostream>
#include <list>
    using namespace std;
    void * f(int numeraccio) {
        numeraccio++;
        cout << " " << numeraccio << " " << endl;
    };


   int main()
{

    list<void(*)(int )> l;
    l.push_back(f);
    getchar();

    return 0;
}

I get this error

Error C2664 'void std::list<void (__cdecl       *)(int),std::allocator<_Ty>>::push_back(const _Ty &)': impossible to convert the argument 1 from 'void *(int)' to 'void (__cdecl *&&)(int)' 

Upvotes: 0

Views: 5429

Answers (3)

AndOr
AndOr

Reputation: 1

You can use cflow

cflow -d 1 -b --omit-arguments --omit-symbol-names FILE_NAME.c | sed 's/<.*>://' > ~/LIST_FUN

Upvotes: 0

Mohit
Mohit

Reputation: 1295

Another solution might be the use of std::function<void(int)>.

#include "stdafx.h"
#include <string>
#include <iostream>
#include <list>
#include <functional>

using namespace std;
    void f(int numeraccio) { // removed '*' because you are not returning anything
        numeraccio++;
        cout << " " << numeraccio << " " << endl;
    };


int main()
{

    list<std::function<void(int)> > l; // see this line 
    l.push_back(f);
    getchar();

    return 0;
}

Upvotes: -2

Tyker
Tyker

Reputation: 3047

void(*)(int ) is the type of a function pointer returning void not void*

the pointer on function that you need for f is void*(*)(int )

and f need a return statement

or as PaulR said, you don't want you function to return anything and your funtion pointer is good but your function declaration should be

void f(int numeraccio)

insteald of

void * f(int numeraccio)

Upvotes: 7

Related Questions