creating a std::vector of a templated class?

2019-09-01 13:39发布

问题:

I currently have a class that uses template arguments. I need an array of these. How could I do this (without boost). ex:

template <typename RET, typename T>
class AguiTimedEvent {
    RET (*onEvent)(T arg);
    double timeStamp;
public:
    RET call(T arg);
    bool expired();
    AguiTimedEvent();
    AguiTimedEvent(RET (*Timefunc)(T arg), double timeSec);
};

and I would need to something like:

AguiTimedEvent t<int, int>(func, 5.0);
v.push_back(t);
...
v[0].call();

I don't actually need the return value, but I just have it to make it more flexible. If the return value causes an issue I could limit it to void functions, but defiantly the arg needs to be templated. What can I do? Thanks

*I need the vector to handle any type, I need an array, where the array can dispatch events of X Y, not just int int

回答1:

std::vector<AguiTimedEvent<int, int> > v;

If you need to store objects of different AguiTimedEvent types that have different template arguments, you need to create a base class (e.g., AguiTimedEventBase) and store pointers in the vector.



回答2:

I didn't face a problem with the following code:

template <typename RET, typename T>
class AguiTimedEvent {
    RET (*onEvent)(T arg);
    double timeStamp;
public:
    RET call(T arg) {return 0;}
    bool expired() {}
    AguiTimedEvent() {}
    AguiTimedEvent(RET (*Timefunc)(T arg), double timeSec) {}
};

int func(int x) {return 0;}

int main()
{
    vector< AguiTimedEvent<int, int> > v;
    AguiTimedEvent<int, int> t(func, 5.0);

    v.push_back(t);

    return 0;
}