Deducing类型,当使用成员函数指针作为模板参数时 [英] Deducing type, when using member function pointer as template argument
问题描述
当我想有成员函数作为模板参数时,是否有一种方法来to化它,而不提供 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<一世; }
};
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不是类... $ c $因此,有没有办法让编译器推导出Caller类型?
解决方案不,不是你想要的。
如果
,则可以推导出调用者
模板< class Caller>
void call(Caller * c,void(Caller :: * Func)(int)){(c-> * Func)(6); }
例如,您可以使调用看起来像这样:
f.arg(this).call< printNumber>();
调用
函数看起来类似于:
模板< class Arg>
struct Binder
{
template< void(Arg :: * Func)(int)>
void operator()()const {
...
}
};
arg
函数很容易写(在您的情况下,它会返回 Binder< Bar>
,其中 Bar
是从
When I want to have member function as template argument, is there a way to templetize it without providing Caller
type?
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;
}
when I try
template <void (Caller::*Func)(int), typename Caller>
void call(Caller * c) { (c->*Func)(6); }
and call it like
f.call<&Bar::printNumber>(this);
I am getting Caller is not class...
error.
So, is there a way to let compiler deduce the Caller type?
No, not as you want it. Caller
could be deduced if
the pointer to member function were an parameter, not a template parameter. Eg:
template <class Caller> void call(Caller * c, void (Caller::*Func)(int)) { (c->*Func)(6); }
it was known beforehand. For example, you could make the call look like this:
f.arg(this).call<&Bar::printNumber>();
The
call
function would look similar to this:template <class Arg> struct Binder { template<void (Arg::*Func)(int)> void operator()() const { ... } };
The
arg
function would be easy to write (in your case it would returnBinder<Bar>
, whereBar
is deduced fromthis
).Not very convenient, IMHO.
这篇关于Deducing类型,当使用成员函数指针作为模板参数时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!