c++ - C语言联动typedef & templates

标签 c++ c templates typedef linkage

我知道模板不能出现在 extern "C" block 中,原因是实例化模板函数的 name 不能出现一次多于一次使用未损坏的名称。

然而,在下面的代码中,函数的名称​​被破坏了(所以应该没有问题,因为每个实例化都会有一个唯一的名称)但仍然具有与 C 语言链接的函数类型.我的问题是下面的代码是否格式正确:

extern "C" using fn_type = void();

template<typename T>
fn_type foo;

int main()
{
    fn_type* const p = foo<int>;
    p();
}

编辑:仅通过编译器运行它很难测试它是否符合要求,因为 GCC、Clang 和 MSVC 不区分 C++ 和 C 函数指针类型。

最佳答案

对我来说,标准似乎并没有 100% 清楚这一点。唯一提到模板和链接的相关部分是 C++11,[temp]§4:

A template name has linkage (3.5). A non-member function template can have internal linkage; any other template name shall have external linkage. Specializations (explicit or implicit) of a template that has internal linkage are distinct from all specializations in other translation units. A template, a template explicit specialization (14.7.3), and a class template partial specialization shall not have C linkage. Use of a linkage specification other than C or C++ with any of these constructs is conditionally-supported, with implementation-defined semantics. [...]

(强调我的)

段落以具有链接的模板名称 开头。然后它说“funciton template (notname) can have internal linkage;任何其他模板名称 都应具有外部链接。”

对我来说,这似乎暗示模板的链接是指模板的名称的链接。如果该解释是正确的,那么您的示例格式正确,如粗体所示部分也适用于模板名称。那么没有什么能阻止函数模板类型具有 C 链接。

这就是我对标准的解释。

关于c++ - C语言联动typedef & templates,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19448165/

相关文章:

c++ - SDL_Delay 不会在每个 Action 之前延迟

c++ - 错误 :"error LNK2019: unresolved external symbol"

php - 为什么 C 打印的值与 PHP 打印的值不同?

c++ - 使用模板参数模板解决不明确调用的 C++ 默认行为是什么?

c++ - 获取地址时模板类型(类/函数)实例化的规则是什么?

c++ - 如何判断哪些参数是必需的,哪些不是? (视觉 C++)

c - 使用数组存储大数

c - 使用结构、引用和 gettimeofday 函数的一些帮助

c++ - 指向抽象模板基类的指针?

c++ - 模板类中 `is_base_of` 的静态断言因 MSVC 中的意外类型而失败