在C++同名的顶级函数之间进行选择
Choose between C++ top-level functions of the same name
我的C++项目huzzah
有一个顶级标头include/huzzah.h
,用于定义两个函数do_this
和do_that
.我在src/thing1.cpp
和src/thing2.cpp
中有多个这些功能的实现。给定以下单元测试,如何指定使用函数的do_this或do_that实现?也许在huzzah/CMakeLists.txt
,还是通过main
args?
#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
相关文章:
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- 在 const 函数中通过引用和指针返回之间的区别
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 构造函数和转换运算符之间的重载解析
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- 编译器如何在使用SFINAE的函数和标准函数之间确定两者是否可行
- 为什么 c++(g++) 不允许模板返回类型和函数名称之间有空格?
- 填充上编译器生成的复制构造函数之间的不一致
- 析构函数和'delete'之间的区别
- 为什么不允许成员函数和非成员函数之间的函数重载?
- 函数签名与调用的函数不匹配,常量字符[]和字符*之间的区别?
- 如何在"push_*()"和"emplace_*()"函数之间进行选择?
- 内联函数的函数本地静态对象是否在共享对象文件之间共享?
- 派生类(构造函数具有参数)和基类(构造函数缺少参数)之间没有可行的转换
- 在"template"和函数声明之间使用:template<typename trait> using tr = base_trait<trait> void fn(tr::t
- 在 C 和 C++ 中作为函数参数,int **a 和 int a[][] 之间有什么确切的区别
- 定义类模板构造函数的两种方法之间的区别
- 仅具有运算符()的结构和普通函数之间的实际区别
- 可变/非可变模板之间函数类型衰减的不一致性