c++ - 使用 MSVC 在外部“C”中返回模板类的替代方法
问题描述
我有以下课程(以及某些类型的一些专业化):
template <typename Type>
class SimpleOptional {
public:
SimpleOptional(Type content) : value_(true), content_(content) {}
// obviously simplified...
private:
bool value_;
Type content_;
};
这是外部函数接口的一部分。该函数必须extern "C"
像这样声明:
extern "C" SimpleOptional<char*> b(char *a) {
return a + 4; // implicitly constructing SimpleOptional<char*>
}
此代码适用于 macOS 和 Linux 上的 GCC 和 Clang。但是 MSVC 不喜欢它并抱怨带有 C 链接的函数可能不会返回 C++ 类。
到目前为止,我想出了这个(其中 MS_O 只会为 MSVC 定义):
template <typename Type>
class SimpleOptional {
public:
SimpleOptional(Type content) : value_(true), content_(content) {}
using ContentType = Type;
private:
bool value_;
Type content_;
};
#define MS_O(type) struct { bool b; type::ContentType v; }
extern "C" MS_O(SimpleOptional<char*>) b(char *a) {
return a + 4;
}
尽管这解决了返回类型问题,但我仍然没有隐式构造,MSVC 抱怨无法将 char* 转换为返回类型。
是否有任何不花费我 C++ 隐式构造的解决方法?
解决方案
推荐阅读
- excel - 如何使用偏移函数在excel中获取不同数据集的斜率?
- c++ - 高斯模糊缩小缩放图像?
- django - 无法在 django 视图中使用 PUT Ajax 请求接收数据值
- c# - Swagger Swashbuckle 路线阻塞
- python - DBSCAN kdist-绘制多个山谷
- c++ - 流行的 vscode #include iostream 错误
- python - Python:按创建日期或文件名中的数字列出目录中的XML文件
- python - discord.py 和 youtube_dl,“读取错误”和“会话因某种原因已失效”
- python - Python ASCII 绘图仪
- css - 在tailwaindcss中自定义过渡