问题
I currently have a problem, VS2010 nags that "TFunctionPointer" used in the constructor of "Nuke" & as datamember is undefined. Could someone please explain to me why this is ? Any help is very much appreciated.
template<typename T>
typedef void (T::* TFunctionPointer)();
class Nuke
{
public:
Nuke( TFunctionPointer pFunction );
virtual ~Nuke();
private:
TFunctionPointer m_pFunction;
};
// EDIT
What I'm trying to do is allow a function pointer to any type of class to be stored and called on destruction of the Nuke object. A twist on RAII. But I guess it isn't possible. Thanks for the help guys.
// EDIT
Apparently Boost::shared_ptr is what I was looking for.
回答1:
Template typedefs aren't legal in C++.
What you can do though (in both "old" and "new" C++) is this:
template <typename T>
struct TFunctionPointer
{
typedef void (T::*Type)();
};
class Nuke
{
public:
Nuke( TFunctionPointer<Nuke>::Type pFunction );
virtual ~Nuke();
private:
TFunctionPointer<Nuke>::Type m_pFunction;
};
回答2:
C++ doesn't support template typedefs, so template<typename T> typedef
is illegal.
If you can use C++11 you might be able to use template aliases. I'm not quite sure if that is possible with memberfunction pointers and can't guarantee the syntax is correct, but I would expect it to be something like the following:
template <typename T>
using TFunctionPointer = void(T::*)();
Of course VS2010 probably doesn't support that anyways.
Anyways your Nuke
class doesn't give a type for the TFunctionPointer
, so even if that typedef where legal, you are trying to pass a template instead of a concrete type, which isn't possible.
You could wrap your function pointer into a type and use a properinstantiation:
template<typename T> struct FunctionPointer { typedef void (T::*Type)(); };
class Nuke {
public:
Nuke(FunctionPointer<Nuke>::Type pFunction);
virtual ~Nuke();
private:
FunctionPointer<Nuke>::Type m_pFunction;
};
来源:https://stackoverflow.com/questions/10115048/template-member-function-pointers