首页 > 解决方案 > 使用 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++ 隐式构造的解决方法?

标签: c++visual-c++

解决方案


推荐阅读