2012-04-19 221 views
3

当我想将成员函数作为模板参数时,有没有一种方法可以在不提供Caller类型的情况下进行构造?使用成员函数指针作为模板参数时的演绎类型

struct Foo 
{ 
    template <typename Caller, void (Caller::*Func)(int)> 
    void call(Caller * c) { (c->*Func)(6); } 
}; 

struct Bar 
{ 
    void start() 
    { 
     Foo f; 
     f.call<Bar, &Bar::printNumber>(this); 
       ^^^^ 
    } 

    void printNumber(int i) { std::cout << i; } 
}; 

int main() 
{ 
    Bar b; 
    b.start(); 
    return 0; 
} 

当我尝试

template <void (Caller::*Func)(int), typename Caller> 
void call(Caller * c) { (c->*Func)(6); } 

,并调用它像

f.call<&Bar::printNumber>(this); 

我得到Caller is not class...错误。

那么,有没有办法让编译器推断出来电类型?

回答

2

不,不是你想要的。如果

  1. 指针构件功能均一个参数,而不是一个模板参数Caller可以推断。例如:

    template <class Caller> 
    void call(Caller * c, void (Caller::*Func)(int)) { (c->*Func)(6); } 
    
  2. 它是事先知道的。例如,你可以拨打电话是这样的:

    f.arg(this).call<&Bar::printNumber>(); 
    

    call功能将类似于此:

    template <class Arg> 
    struct Binder 
    { 
        template<void (Arg::*Func)(int)> 
        void operator()() const { 
        ... 
        } 
    }; 
    

    arg功能会很容易写(在你的情况下,它会返回Binder<Bar>,其中Barthis推导)。

    不是很方便,恕我直言。

+0

非常感谢!我甚至不知道为什么我会尝试将它代替常规参数进行构造:)再次感谢您 – relaxxx 2012-04-19 16:41:14