在C++同名的顶级函数之间进行选择

Choose between C++ top-level functions of the same name

本文关键字:之间 函数 行选 选择 C++      更新时间:2023-10-16

我的C++项目huzzah有一个顶级标头include/huzzah.h,用于定义两个函数do_thisdo_that.我在src/thing1.cppsrc/thing2.cpp中有多个这些功能的实现。给定以下单元测试,如何指定使用函数的do_this或do_that实现?也许在huzzah/CMakeLists.txt,还是通过mainargs?

#include "huzzah.h"
int main(int argc, char **argv) {
auto a = do_this;
auto b = do_that;
std::cout << "a = " << a << std::endl;
std::cout << "b = " << b << std::endl;
}

(我不想把它们变成 Thing1 和 Thing2 类。

您可以为每个 cpp 文件创建 2 个共享库(在 cmake 中(:

add_library(thing1 SHARED src/thing1.cpp)
add_library(thing2 SHARED src/thing2.cpp)

然后使用 DLPone/DLSim 动态加载它们(不要将您的应用程序与这些库链接(:

using do_this_f = decltype(&do_this);
auto handle = dlopen( "libthing1.so", RTLD_LAZY );
auto do_this_1 = reinterpret_cast<do_this_f>( dlsym( handle, "do_this" ) );
do_this_1(); // calling do_this from libthing1.so

当然,您需要添加错误处理,lib的正确路径等

这比看起来容易:

#include "huzzah.h"
int main(int argc, char **argv) {
auto a = do_this();
auto b = do_that();
std::cout << "a = " << a << std::endl;
std::cout << "b = " << b << std::endl;
}
g++ -o test1 testmain.cpp src/thing1.cpp
g++ -o test2 testmain.cpp src/thing2.cpp
相关文章: