问题
I am facing a problem with templated member function pointer. The code is as shown below.
#include <String>
#include <iostream>
template<typename T>
struct method_ptr
{
typedef void (T::*Function)(std::string&);
};
template <class T>
class EventHandler
{
private:
method_ptr<T>::Function m_PtrToCapturer;
};
e:\EventHandler.h(13) : error C2146: syntax error : missing ';' before identifier 'm_PtrToCapturer'
I am facing this error.
Even If I use
method_ptr<EventHandler>::Function m_PtrToCapturer;
as member variable I am getting same error as above.
回答1:
Because method_ptr<T>::Function
is a dependent name (dependent on T
), you need to disambiguate it with typename
:
template <class T>
class EventHandler
{
private:
typename method_ptr<T>::Function m_PtrToCapturer;
// ^^^^^^^^
};
回答2:
This works,
struct method_ptr
{
typedef void (T::*Function)(std::string&);
};
template <class T>
class EventHandler
{
private:
typename method_ptr<T>::Function m_PtrToCapturer;
};
回答3:
Since C++11, you can use using
.
template <typename T>
using Function = void (T::*)(std::string);
(By the way, why is std::string
called-by-value? I recommend const std::string &
.)
Aha, I figured out your second question.
template <typename T>
method_ptr<T>::Function m_PtrToMemFunc; //<--
template is only applied to class and function (and cpp11's typedef&using...). you should write like this.
method_ptr<SomeClass>::Function m_PtrToMemFunc;
来源:https://stackoverflow.com/questions/21863194/templated-function-pointer-in-c