C++中的模板化函数指针

Templated Function Pointer in C++

本文关键字:函数 指针 C++      更新时间:2023-10-16

我遇到了模板化成员函数指针的问题。代码如下所示。

#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):错误 C2146:语法错误:标识符"m_PtrToCapturer"之前缺少";"

我正面临此错误。

即使我使用

method_ptr<EventHandler>::Function m_PtrToCapturer;

作为成员变量,我得到与上述相同的错误。

因为method_ptr<T>::Function是一个依赖名称(依赖于T),所以你需要用typename来消除歧义:

template <class T>
class EventHandler
{
private:
    typename method_ptr<T>::Function m_PtrToCapturer;
//  ^^^^^^^^
};

这有效,

struct method_ptr
{
    typedef void (T::*Function)(std::string&);
};
template <class T>
class EventHandler
{
private:
    typename method_ptr<T>::Function m_PtrToCapturer;
};

从 C++11 开始,您可以使用 using .

template <typename T>
using Function = void (T::*)(std::string);

(顺便问一下,为什么std::string按值调用?我推荐const std::string &


啊哈,我想通了你的第二个问题。

template <typename T>
method_ptr<T>::Function m_PtrToMemFunc; //<--

模板仅适用于类和函数(以及CPP11的typedef&using...)。 你应该这样写。

method_ptr<SomeClass>::Function m_PtrToMemFunc;