mercredi 2 janvier 2019

In a class constructor, define a vector of T type

I can already define a function pointer vector with a fixed parameter type in the public: header, then update it in the constructor. But, if I want to be able to pass a function pointer vector with a parameter of any type, how can I define it before the constructor updates it?

#include <iostream>
#include <vector>

class foo {
public:
    std::vector<void (*)(int)> functions;

    foo(std::vector<void (*)(int)> x) {
        functions=x;
    }

    void run() {
        functions[0](2);
    }
};

void square(int n) { std::cout << n*n; }

int main() {
    foo* bar=new foo(std::vector<void (*)(int)>{square});
    bar->run();
    return 0;
}

Now, how could I pass a vector to the constructor with any type?

//snippet from above
std::vector<void (*)()> functions; //what do i do here?

template <typename T>   
foo(std::vector<void (*)(T)> x) { //this works fine
    functions=x;
}

Aucun commentaire:

Enregistrer un commentaire