Domanda

I want to define a class template that takes a callback function of the same type. Something like:

    typedef template<class T> bool CallbackFn( T x );

    template<class T> class MyClass
    {
    public:
        MyClass() {}
        ~MyClass() {}
        void addCallbackFn( CallbackFn* fn ) { callbackFn = fn; }
    private:
        CallbackFn* callbackFn;
    };

And it would be used like this:

    bool testFunctionInt(int x) { return true; }
    bool testFunctionString(std::string x) { return true; }

    MyClass<int> a;
    a.addCallbackFn( testFunctionInt );

    MyClass<std::string> b;
    b.addCallbackFn( testFunctionString );

Unfortunately the callback function cannot be defined as a function template via the typedef.

Is there another way to do this?

È stato utile?

Soluzione

#include <string>

template <typename T>
class MyClass {
  public:
    typedef bool CallbackFn(T x);

    MyClass() : cb_(NULL) {}
    ~MyClass() {}

    void addCallbackFn(CallbackFn *fn) { cb_ = fn; }

  private:
    CallbackFn *cb_;
};

static bool testFunctionInt(int x) { return true; }
static bool testFunctionString(std::string x) { return true; }

int main()
{
    MyClass<int> a;
    a.addCallbackFn( testFunctionInt );

    MyClass<std::string> b;
    b.addCallbackFn( testFunctionString );
}

Altri suggerimenti

Move the typedef inside of the class like this:

template<class T> class MyClass
{
public:
    MyClass() {}
    ~MyClass() {}
    typedef bool CallbackFn( typename T x );
    void addCallbackFn( CallbackFn* fn ) { callbackFn = fn; }

    //you could also do this
    typedef bool (*CallbackFnPtr)(typename T x);
    void addCallbackFnPtr(CallbackFnPtr fn ) { callbackFn = fn; }

private:
    CallbackFn* callbackFn;  //or CallbackFnPtr callbackFn;
};

I'm assuming you meant MyClass<std::string> b; in your example.

I made some changes.

template<class T>
class MyClass
{

public:
    typedef bool (*CallbackFn)( T x );

    MyClass() {}
    ~MyClass() {}
    void addCallbackFn( CallbackFn fn ) { callbackFn = fn; }
private:
    CallbackFn callbackFn;
};

bool testFunctionInt(int x) 
{
    return true; 
}

int main(int argc, char * argv[])
{

    MyClass<int> c;
    c.addCallbackFn(testFunctionInt);
    return 0;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top