非静态成员函数模板地址

时间:2021-02-12 03:37:48

标签: c++ templates static member-function-pointers

我想了解是否可以获取非静态成员函数模板的地址。下面不起作用,使用 &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>;

1 个答案:

答案 0 :(得分:1)

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

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

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

(this->*z)();