非静态成员函数reinterpre_cast失败

non-static member function reinterpret_cast failed

本文关键字:cast 失败 reinterpre 静态成员 函数      更新时间:2023-10-16

代码:

#include <iostream>
using namespace std;
struct item
{
   int f1() {}
   double f2() {}
   static int  g1() {}
   static double  g2() {}
   void f0();
};
void item::f0()
{
   auto c1 = reinterpret_cast<decltype(f2)>(f1);
   auto c2 = reinterpret_cast<decltype(g2)>(g1);
   auto c3 = reinterpret_cast<decltype(&f2)>(f1);
   auto c4 = reinterpret_cast<decltype(&g2)>(g1);
}
int main()
{
   cout << "Hello world!" << endl;
   return 0;
}

错误消息:

main.cpp|17|error: invalid use of non-static member function|
main.cpp|18|error: invalid cast from type ‘int (*)()’ to type ‘double()’|
main.cpp|20|error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.  Say ‘&item::f2’ [-fpermissive]|
main.cpp|20|error: invalid use of member function (did you forget the ‘()’ ?)

我的问题:作为参数传递的成员函数将自动转换为指针,所以我尝试将参数强制转换为指针但仍然失败。我不明白为什么非静态成员函数根本不起作用情况

您需要强制转换f1的返回值,而不是f1。用途:

  auto c1 = reinterpret_cast<decltype(f2())>(f1());
                                               ^^ Call the function

对其他行进行类似的更改。

我误解了你想做的事情。以下应该有效:

   auto c1 = reinterpret_cast<decltype(&item::f2)>(&item::f1);
   auto c2 = reinterpret_cast<decltype(&g2)>(g1);
   auto c3 = reinterpret_cast<decltype(&item::f2)>(&item::f1);
   auto c4 = reinterpret_cast<decltype(&g1)>(g2);

f1是一个非static成员函数。您可以使用f1()来调用它。但是,如果没有函数调用语法,非静态成员函数不会自动衰减为成员函数指针。要获得struct的成员函数指针,您需要使用&item::f1