gpt4 book ai didi

c++ - 究竟如何实现分配自动更新

转载 作者:太空宇宙 更新时间:2023-11-03 10:34:35 26 4
gpt4 key购买 nike

考虑以下代码:

struct data
{
int foo;
int bar;
};

data a;
a.foo = 200;
a.bar = 300;

static void update(data* a, int rspec)
{
if (!rspec) //my data management
{
3rdPartyApi->CreateStream();
3rdPartyApi->PushData(a->foo);
3rdPartyApi->PushData(a->bar);
3rdPartyApi->CloseStream();
}
else // internal data management
{
3rdPartyApi->CreateStream();
3rdPartyApi->PushData(3rdPartyApi->BufferQueue);
3rdPartyApi->CloseStream();
}
3rdPartyApi->PushStream(3rdPartyApi->GetLastStreamBuffer().POD());
}

假设我更改了 a.foo 或 a.bar 的值,它要求我在赋值后调用 Update。可以做到这一点,而无需在每次更改时手动实际调用 Update() 吗?

[编辑]
请注意,创建的更新函数也被分配给一个函数指针第三方 API,因此它可以进行自己的内部更新。所以使更新函数成为非全局的是不可能的,这就是为什么当前的更新函数是全局的。
[编辑]
我还重写了我的示例,以便更好地理解和更正我正在使用的实际 API

例如

3rdPartyApi->StreamUpdate((void (*)(void*, int))update);

最佳答案

是的,你可以。为此使用类方法。将您的类中的静态方法作为更新函数传递给第 3 方 API。

class data
{
public:
void set_foo(int new_foo);
void set_bar(int new_bar);

int get_foo() const;
int get_bar() const;

// This is the update signature which the 3rd party API can accept.
static void update(void* ptr, int rspec);

private:
// These are private so we can control their access.
int foo;
int bar;
};

void data::set_foo(int new_foo)
{
foo = new_foo;
// 'this' is a special pointer for current data object.
update(this);
}

void data::set_bar(int new_bar)
{
bar = new_bar;
update(this);
}

int data::get_foo() const
{
return foo;
}

int data::get_bar() const
{
return bar;
}

// This is needed if the 3rd party API can only call C bindings.
// If it's a C++ API this is not needed.
extern "C" {

void data::update(void* ptr, int rspec)
{
if (!rspec) //my data management
{
// You have to cast to data* from void*.
data* data_ptr = reinterpret_cast<data*>(ptr);

3rdPartyApi->CreateStream();
3rdPartyApi->PushData(data_ptr->foo);
3rdPartyApi->PushData(data_ptr->bar);
3rdPartyApi->CloseStream();
}
else // internal data management
{
3rdPartyApi->CreateStream();
3rdPartyApi->PushData(3rdPartyApi->BufferQueue);
3rdPartyApi->CloseStream();
}
3rdPartyApi->PushStream(3rdPartyApi->GetLastStreamBuffer().POD());
}

} /* extern "C" */

然后:

3rdPartyApi->StreamUpdate(&data::update);
data a;
a.set_foo(200);
a.set_bar(300);

请注意,使用 struct 而不是 class 在这里同样可以。但惯例是在 C++ 中使用类。只有细微差别,您可以稍后了解。

关于c++ - 究竟如何实现分配自动更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6489128/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com