带有模板的 C++ 函数指针

Posted

技术标签:

【中文标题】带有模板的 C++ 函数指针【英文标题】:C++ function pointer with templates 【发布时间】:2015-11-06 19:55:34 【问题描述】:

我正在尝试存储指向成员函数的指针。需要存储指针的类声明为:

template <typename TDataType, typename T>
bool my_function(std::string topic_name,
                 void(T::*)(const TDataType&) fp,
                 T* obj)

我得到错误:

error: expected ',' or '...' before 'fp'
                               void(T::*)(const TDataType&) fp,

谁能告诉我发生了什么事?看起来这是我没有得到的语法错误。

【问题讨论】:

【参考方案1】:

变化:

void(T::*)(const TDataType&) fp

void(T::* fp)(const TDataType&)

【讨论】:

【参考方案2】:

成员函数指针的语法是

return_type(class_name::* function_pointer_name)(function_parameters)

所以

template <typename TDataType, typename T>
bool my_function(std::string topic_name,
                 void(T::*)(const TDataType&) fp,
                 T* obj)

需要

template <typename TDataType, typename T>
bool my_function(std::string topic_name,
                 void(T::* fp)(const TDataType&)'
                 T* obj)

【讨论】:

以上是关于带有模板的 C++ 函数指针的主要内容,如果未能解决你的问题,请参考以下文章