Reputation: 785
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?
Upvotes: 1
Views: 139
Reputation: 290
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;
}
Upvotes: 1
Reputation:
#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 );
}
Upvotes: 3
Reputation: 6821
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.
Upvotes: 2