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 に答える