2

我有

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

所以2个问题:

1、(m_caller->*T)(e);正确吗?如果不是,我怎么叫它?

2、如何实例化它?

4

2 回答 2

1
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);
于 2012-04-14T13:33:16.713 回答
0

编辑:

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;
}
于 2012-04-14T13:40:56.087 回答