首页 > 解决方案 > 非静态成员函数模板地址

问题描述

我试图了解是否可以获取非静态成员函数模板的地址。以下不起作用,使用&sz<int>会导致其他错误。获取非静态成员函数模板地址的正确方法是什么?

311 struct XYZ
312 {
313    template <typename Z>
314    void sz()
315    {
316    }
317 
318    void func()
319    {
320       auto z = sz<int>;
321    }
322 };

导致错误

vs.cc:320:16: error: reference to non-static member function must be called; did you mean to call it with no arguments?
      auto z = sz<int>;

标签: c++templatesstaticmember-function-pointers

解决方案


void sz()模板无关紧要,因为sz<int>它是成员函数。C++ 中没有“地址”的概念——这是一个实现细节。你可以拥有一个指向成员函数的指针,它的语法是:

auto z = &XYZ::sz<int>;

要在内部调用它func(),您需要以下语法:

(this->*z)();

推荐阅读