非静态成员函数reinterpret_cast失败

时间:2016-10-18 04:47:48

标签: c++ member non-static reinterpret-cast

代码:

#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 ‘()’ ?)

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

1 个答案:

答案 0 :(得分:0)

您需要转换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