C++ 调用结构体函数的指针

问题描述 投票:0回答:1

我在下面有一个简单的代码:

int global1(int x)
{
 return x * 5;
}

int global2(int x)
{
 return x + 5;
}

struct some_struct {
  int a;

  int foo1(int x)
  {
     return x * a;
  }

  int foo2(int x)
  {
     return x + a;
  }

  int bar1(int x, bool a)
  {
     auto func = a ? global1 : global2; // works
     // auto func = a ? &global1 : &global2; // also works

     return func(x);
  }

  int problem_function(int x, bool a) // It is my question
  {
     auto func = a ? foo1 : foo2; // gives error
     // auto func = a ? &foo1 : &foo2; // also gives error
     // auto func = a ? &this->foo1 : &this->foo2; // also gives error

     return func(x);
  }
};

这是真实代码的非常简单的形式,我无法像我在 global1() 和 global2() 中所做的那样在外部携带函数

我想调用结构体中的函数之一,但使用指向函数的指针,但它给出了错误。

注意:我不能使用 if else 因为在真实代码中它不返回 func(x) 在真实代码中我使用 func(x) 作为循环中函数的条件(我不是在开玩笑)

真实代码的一部分:

void* find_first(ExprToken* (*cond)(bool (*)(ExprToken*))) {...} // yeah

我知道如果我想调用结构体的函数,我必须告诉编译器我正在使用哪个变量(结构体),但是如何调用。

C++ 也支持结构体中的函数指针吗?

对于复杂性感到抱歉,甚至有时我忘记真正的代码实际上在做什么。

c++ pointers struct function-pointers
1个回答
0
投票

资源:https://public.websites.umich.edu/~eecs381/handouts/Pointers_to_memberfuncs.pdf

我在网上找到了答案,我想在这个问题下分享。

答案:

  int problem_function(int x, bool a) // It is my question
  {
     auto func = a ? &some_struct::foo1 : &some_struct::foo2;

     return (*this).*func(x);
  }
© www.soinside.com 2019 - 2024. All rights reserved.