考虑用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::variant
和std::any
出现在C++17
中。
有没有一种方法可以避免在全局命名空间中为所有支持的类型添加单独的函数?
不,因为您要做的是为每种类型实例化模板,并使其从C中可用,所以您必须为每一种类型定义它。