2009-07-29 137 views
2

是否可以传递函数指针作为模板参数而不使用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? 
} 
+0

虽然没有传递函数指针作为模板参数,但它正在传递类型_函数指针。 – leftaroundabout 2012-03-27 14:06:43

回答

11

是:

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

这是一样服用typedef声明和去除typedef关键字和名称。

3

这是完全可能的, 我也建议查找boost :: function & boost :: bind作为替代解决方案。

0

我不能像Maciek建议的那样使用boost(例如,您不能在项目中使用外部库),您可能会尝试使用函子。