使用C链接在函数内部创建C++模板



考虑用C++11编写的共享库myLib和用C++17编写的调用myLib中函数的可执行myExe。然而,myExe是由不同的编译器编译的,因此两者使用C链接链接在一起,myLib的标头负责处理这一点。一旦进入myLib,我希望在代码中尽早使用模板来享受C++的特权。有没有一种方法可以避免在全局命名空间中为所有支持的类型添加单独的函数?我可以控制两者的源代码。

例如,在myLib中,我想避免:

// Exported function for int
void myCLinkedFuncForInt(int A)
{
// templated C++ internal function for myLib
myLib::myFunc(A);
}
// Exported function for float
void myCLinkedFuncForFloat(float A)
{
// templated C++ internal function for myLib
myLib::myFunc(A);
}

其中我将CCD_ 11定义为模板。

我尝试过一些有趣但不安全的东西:

void myCLinkedFuncForEverything(void* A, const char* type)
{
const std::string CppType(type);
if (CppType == "int")
return myLib::myFunc(*(reinterpret_cast<int*>(A));
if (CppType == "float")
return myLib::myFunc(*(reinterpret_cast<float*>(A));
// If we reached here, we are unsupported
std::cout << "Data type not supported" << std::endl;
}

然后在myExe中,我将所有内容强制转换为void*并提供type。对于C++11,我还有哪些其他选项?

注:std::variantstd::any出现在C++17中。

有没有一种方法可以避免在全局命名空间中为所有支持的类型添加单独的函数?

不,因为您要做的是为每种类型实例化模板,并使其从C中可用,所以您必须为每一种类型定义它。

最新更新