Question

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.

Was it helpful?

Solution

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;
//  ^^^^^^^^
};

OTHER TIPS

This works,

struct method_ptr
{
    typedef void (T::*Function)(std::string&);
};

template <class T>
class EventHandler
{

private:
    typename method_ptr<T>::Function m_PtrToCapturer;
};

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top