[英]Deducing type, when using member function pointer as template argument
当我想将成员函数作为模板参数时,是否有办法在没有提供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...
错误。
那么,有没有办法让编译器推断出Caller类型?
不,不是你想要的。 Caller
可以推断,如果
指向成员函数的指针是参数,而不是模板参数。 例如:
template <class Caller> void call(Caller * c, void (Caller::*Func)(int)) { (c->*Func)(6); }
它是事先知道的。 例如,您可以使调用看起来像这样:
f.arg(this).call<&Bar::printNumber>();
call
函数看起来类似于:
template <class Arg> struct Binder { template<void (Arg::*Func)(int)> void operator()() const { ... } };
该arg
功能会很容易写(在你的情况下,它会返回Binder<Bar>
,在Bar
从推断this
)。
不太方便,恕我直言。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.