是否可以跨动态库模拟函子作用域的成员函数调用上下文?

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

给定一个简单的 Api 对象:

// api.h
struct Api {
  int foo(int c);
  int bar(int a, int b);
};

它可以按以下格式使用:

// api users 
struct InApi : Api {
  int memfoo() {
    return bar(2, foo(5));
  }
};

int extfoo(Api * api) {
  return api->bar(2, api->foo(5));
}

但是这个呢? (假设,寻找实现结果的具体方法)

// outside of Api class, but as if in
int desiredFormat = [/*capture implicit this context*/](Api *)->{
  return bar(2, foo(5)); // no this-> required to resolve
}(api);

是否可以以类似于所需格式的方式模拟函子作用域的成员函数调用上下文,以及如何模拟?

如果可能的话,跨由同一进程加载的二进制兼容动态库执行此操作是否会出现任何潜在的复杂性?

澄清一下 - 目标是让伪 this 指针在调用上下文中隐式解析 - 无需显式

this->
api->
,而上下文对象指针仍在调用点显式传递。

c++ functor calling-convention this-pointer callcontext
1个回答
0
投票

是否可以以类似于所需格式的方式模拟函子作用域的成员函数调用上下文,以及如何模拟?

不,不是。

您作为 lambda 函数的参数提供的

Api*
无法转换为
this
。 lambda 不会以任何方式构建于
Api
之上,因为它是在非
static
Api
成员函数之外定义的,这是捕获
this
有意义的地方:

struct Api {
    int foo(int c);
    int bar(int a, int b);

    auto get_func() {
        return [this]{ return bar(2, foo(5)); };
    }
};

现在在

get_func()
实例上调用
Api
将返回一个 lambda,您可以稍后使用(当实例处于活动状态时)。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.