简体   繁体   English

关于C ++上模板推导的编译错误

[英]compile error about template deduction on c++

#include <iostream>

template <int N>                                                                         
class X {
public:
  using I = int;                                                                         
  void f(I i) {
    std::cout << "i: " << i << std::endl;
  }
};

template <int N>
void fppm(void (X<N>::*p)(typename X<N>::I)) {
  p(0);
}

int main() {
  fppm(&X<33>::f); 
  return 0;
}

I just don't understand the compile error message of the code. 我只是不了解代码的编译错误消息。

error: called object type 'void (X<33>::*)(typename X<33>::I)' is not a function or function pointer
 p(0);

I think p is a function which returns void and takes int as its argument. 我认为p是一个返回void并以int为参数的函数。 But apparently, it's not. 但显然不是。 Could somebody give me clue? 有人可以给我提示吗?

Since p is a pointer to a nonstatic member function, you need an instance to call it with. 由于p是指向非静态成员函数的指针,因此需要一个实例来调用它。 Thus, first instantiate an object of X<33> in main: 因此,首先在main中实例化X<33>的对象:

int main() {
  X<33> x;
  fppm(x, &X<33>::f); // <-- Signature changed below to accept an instance

Then in your function, change the code to accept an instance of X<N> and call the member function for it: 然后在函数中,更改代码以接受X<N>的实例并为其调用成员函数:

template <int N>
void fppm(X<N> instance, void (X<N>::*p)(typename X<N>::I)) {
  (instance.*p)(0);
}

The syntax may look ugly but the low precedence of the pointer to member operator requires the need for the parentheses. 语法看起来很丑陋,但是指向成员运算符的指针的优先级较低,需要使用括号。

As denoted in the comments already, p is a pointer to member function, but you call it like a static function ( p(0); ). 正如注释中已经指出的那样, p是指向成员函数的指针,但是您将其称为静态函数( p(0); )。 You need a concrete object to call p on: 您需要一个具体的对象来调用p

X<N> x;
(x.*p)(0);
// or:
X<N>* xx = new X<N>();
(xx->*p)(0);
delete xx;

Be aware that the .* / ->* operators have lower precedence than the function call operator, thus you need the parentheses. 请注意, .* / ->*运算符的优先级低于函数调用运算符的优先级,因此需要括号。

Side note: Above is for better illustration, modern C++ might use auto keyword and smart pointers instead, which could look like this: 旁注:上面是为了更好地说明,现代C ++可能会改用auto关键字和smart指针,如下所示:

auto x = std::make_unique<X<N>>();
(x.get()->*p)(0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM