tags:

views:

254

answers:

3

Is it possible to pass a function pointer as a template argument without using a typedef?

template<class PF>
class STC {
    PF old;
    PF& ptr;
public:
    STC(PF pf, PF& p)
        : old(*p), ptr(p) 
    {
        p = pf;
    }
    ~STC() {
        ptr = old;
    }
};

void foo() {}
void foo2() {}

int main() {
    void (*fp)() = foo;
    typedef void (*vfpv)();
    STC<vfpv> s(foo2, fp); // possible to write this line without using the typedef?
}
+7  A: 

Yes:

STC<void (*)()> s(foo2, fp); // like this

It's the same as taking the typedef declaration and removing the typedef keyword and the name.

MSN
+2  A: 

It is totally possible, I'd also recommend looking up boost::function & boost::bind as an alternative solution.

Maciek
A: 

I you cannot use boost as Maciek suggested (e.g. you cannot use external libraries in your project) you might try to use a functor.

fco.javier.sanz