Templated Function Pointer in C++

随声附和 提交于 2019-12-13 07:49:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!