为何在函数指针中使用显式对象参数会触发语法错误?
显式对象参数在函数指针中使用时的MSVC语法错误解决
问题分析
你碰到的syntax error: ')'确实是MSVC对C++23显式对象参数支持不完整导致的——当前MSVC仅在成员函数的声明/定义中支持显式this参数,但不允许将其用于函数指针类型的声明,这就是代码里void(*)(this s& self)位置报错的核心原因。
替代解决方案
如果要兼容MSVC,同时保留设计意图,可以采用以下两种方式:
方案1:用std::function包装(推荐)
MSVC对std::function中的显式this参数支持更完善,替换后可正常编译:
///base.h ///... #include <map> #include <functional> template <class s> using FunctionMap = std::map<std::string, std::function<void(this s& self)>>; class base{ //... public: ///Get Map of fPtr template <class Self> FunctionMap<Self>* get_scripts(this const Self& self); };
方案2:退回到传统成员函数指针(兼容旧编译器)
如果不需要显式this参数的语法糖,可改用传统成员函数指针类型:
///base.h ///... #include <map> template <class s> using FunctionMap = std::map<std::string, void(s::*)()>; class base{ //... public: ///Get Map of fPtr template <class Self> FunctionMap<Self>* get_scripts() const; };
注意这种方式调用成员函数指针时,需要通过对象实例来触发,写法会和显式this参数版本略有差异。
编译器兼容性补充
如果一定要使用显式对象参数的函数指针语法,目前只有GCC 13+和Clang 16+提供了完整支持,可以考虑切换到这两款编译器编译代码。
内容的提问来源于stack exchange,提问作者Nathaniel Burchell
相关产品推荐
相关产品推荐

