简体   繁体   English

如何使用成员函数指针作为模板arg实例化类

[英]How can I instantiate class with Member function pointer as template arg

I have 我有

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;
};

I understand I can instantiate it like 我知道我可以实例化它

Foo f;
Updater<&Foo::Bar> updater(&f);

assuming that Foo has 假设Foo

void Foo::Bar(Entity *e);

but what if it has desired method tempated? 但是如果尝试了所需的方法怎么办? Like this 像这样

template <typename T>
void Bar(T t);

how shoult I instanciate it? 我应该如何表达呢? Like this:? 像这样:?

Foo f;
Updater<&Foo::Bar<Entity *>> updater(&f);

When I do this in my real code, I get 当我在真实代码中执行此操作时,我得到

invalid template argument for ..., expected compile-time constant expression

So 2 questions: 所以有两个问题:

1, is (m_caller->*T)(e); 1是(m_caller->*T)(e); correct? 正确? If it is not, how shout i call it? 如果不是,我怎么喊呢?

2, how can I instantiate it? 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);

edit: 编辑:

user2k5 edited his answer, so I accepted it. user2k5编辑了他的答案,所以我接受了它。

my previous msg: 我以前的味精:

Thanks to user2k5 I figured out the right working code, 多亏了user2k5,我找到了正确的工作代码,

working sample follows: (Foo2 can be replaced by Foo) 工作示例如下:(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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM