[英]How can I instantiate class with Member function pointer as template arg
我有
template <void (*T)(Entity *), typename Caller>
class Updater
{
public:
Updater(Caller c):m_caller(c){}
void process(Entity * e)
{
(m_caller->*T)(e); //Is this right?
}
private:
Caller m_caller;
};
我知道我可以實例化它
Foo f;
Updater<&Foo::Bar> updater(&f);
假設Foo
有
void Foo::Bar(Entity *e);
但是如果嘗試了所需的方法怎么辦? 像這樣
template <typename T>
void Bar(T t);
我應該如何表達呢? 像這樣:?
Foo f;
Updater<&Foo::Bar<Entity *>> updater(&f);
當我在真實代碼中執行此操作時,我得到
invalid template argument for ..., expected compile-time constant expression
所以有兩個問題:
1是(m_caller->*T)(e);
正確? 如果不是,我怎么喊呢?
2,我該如何實例化它?
template <typename Caller, void (Caller::*Func)(Entity *)>
class Updater
{
public:
Updater(Caller *c):m_caller(c){}
void process(Entity * e)
{
(m_caller->*Func)(e); // use pointer to member operator ->*
}
private:
Caller *m_caller;
};
// call like this
Foo f;
Updater<Foo, &Foo::Bar> updater(&f);
編輯:
user2k5編輯了他的答案,所以我接受了它。
我以前的味精:
多虧了user2k5,我找到了正確的工作代碼,
工作示例如下:(Foo2可以被Foo代替)
#include <iostream>
struct Entity { int i; };
template < typename Caller, void (Caller::*Func)(Entity *)>
class Updater
{
public:
Updater(Caller *c):m_caller(c){}
void process(Entity * e)
{
(m_caller->*Func)(e);
}
private:
Caller *m_caller;
};
struct Foo
{
void bar(Entity * e)
{
std::cout << e->i << std::endl;
}
};
struct Foo2
{
template <typename T>
void bar(T t)
{
std::cout << t->i << std::endl;
}
};
int main ()
{
Foo2 f;
Updater<Foo2, &Foo2::template bar<Entity *>> updater(&f);
Entity e;
e.i = 5;
updater.process(&e);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.