C++ 使用成员函数指针作为模板参数时推断类型
当我想让成员函数作为模板参数时,有没有一种方法可以在不提供C++ 使用成员函数指针作为模板参数时推断类型,c++,templates,C++,Templates,当我想让成员函数作为模板参数时,有没有一种方法可以在不提供调用者类型的情况下将其模板化 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, &a
调用者
类型的情况下将其模板化
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;
}
structfoo
{
模板
无效调用(调用方*c){(c->*Func)(6);}
};
结构条
{
void start()
{
福福;
f、 叫(这个);
^^^^
}
void printNumber(inti){std::cout*Func)(6);}
就这样说吧
f.call<&Bar::printNumber>(this);
f.调用(this);
我收到调用方不是类…
错误
那么,有没有一种方法可以让编译器推断调用者类型?没有,不是您想要的。如果
template <class Caller>
void call(Caller * c, void (Caller::*Func)(int)) { (c->*Func)(6); }
arg
函数将易于编写(在您的情况下,它将返回Binder
,其中Bar
是从这个推导出来的)
不太方便
非常感谢!我甚至不知道为什么我尝试将其模板化而不是常规参数:)再次感谢
template <class Caller>
void call(Caller * c, void (Caller::*Func)(int)) { (c->*Func)(6); }
f.arg(this).call<&Bar::printNumber>();
template <class Arg>
struct Binder
{
template<void (Arg::*Func)(int)>
void operator()() const {
...
}
};