gpt4 book ai didi

c++ - C++中如何动态定义成员函数

转载 作者:行者123 更新时间:2023-11-30 02:20:59 25 4
gpt4 key购买 nike

我有这个对象,它只是一个外部 dll 的包装器,在 Windows 中。在创建对象时,构造函数在注册表中查询 key ,然后在包含 dll 的文件夹中查询此 key 的值,然后加载 dll,获取此 dll 的初始化程序的 ProcAddress,并对其进行初始化。

然后,我想向其他客户提供这个 dll 的所有功能,所以我的类包装器提供了成员函数来检查我们是否有 GetProcAddress,如果没有,我们就这样做, 获取指向该函数的指针,并调用它。

我不想在构造函数时执行所有的 GetProcAddress'es,因为有数百个函数,并且给定的客户端很可能只需要其中的一小部分,所以 GetProcAddress'ing 一切都是浪费。

但是现在,我需要定义这些功能,感觉就像是一个巨大的复制粘贴。所有的成员函数都在做完全相同的事情,比如

ResultType Wrapper::pertainingMemberFunction(...)
{
if (this->pointerToPertainingDLLFunction == nullptr) {
this->pointerToPertainingDLLFunction =
reinterpret_cast<pertainingType>(GetProcAddress(HMODULEDLL, "pertainingName"));
}
return this->pointerToPertainingDLLFunction (...);
}

这真的感觉像是一个非常次优的解决方案。我觉得必须有某种方法可以将所有这些代码模板化,以便在编译时正确生成。或者也许最初的方法不是最好的开始,我不确定。

最佳答案

将逻辑提取到函数模板中非常简单:

template <class Function, class... Args>
decltype(auto) getProcAddressAndCall(
Function *&function,
char const *name,
Args &&... args
) {

if(!function)
function = reinterpret_cast<Function *>(GetProcAddress(HMODULEDLL, name));

return function(std::forward<Args>(args)...);
}

...然后您可以调用它:

ResultType Wrapper::pertainingMemberFunction(...)
{
return getProcAddressAndCall(pointerToPertainingDLLFunction, "pertainingName", ...);
}

关于c++ - C++中如何动态定义成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49148714/

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