c++ - 为什么模板不能在 extern "C" block 内?

标签 c++ templates extern linkage

这是 an answer 的后续问题。至Is it possible to typedef a pointer-to-extern-“C”-function type within a template?

此代码无法使用 g++、Visual C/C++ 和 Comeau C/C++ 编译,错误消息基本相同:

#include <cstdlib>

extern "C" {
    static int do_stuff(int) {
        return 3;
    }

    template <typename return_t_, typename arg1_t_>
    struct test {
        static void foo(return_t_ (*)(arg1_t_)) { }
    };
}

int main()
{
    test<int, int>::foo(&do_stuff);
    return EXIT_SUCCESS;
}

g++ 说“错误:带有 C 链接的模板”,Visual C/C++ 发出编译器错误 C2894 ,并且 Comeau C/C++ 说“错误:此声明可能没有外部“C”链接”。

事实是,所有人都很高兴:

#include <cstdlib>

extern "C" {
    static int do_stuff(int) {
        return 3;
    }

    struct test {
        static void foo(int (*)(int)) { }
    };
}

int main()
{
    test::foo(&do_stuff);
    return EXIT_SUCCESS;
}

C++ 标准第 7.5 节,链接规范指出:

A C language linkage is ignored for the names of class members and the member function type of class member functions.

它甚至给出了例子:

extern "C" {
    class X {
        void mf(); // the name of the function mf and the member
                // function's type have C++ language linkage
        void mf2(void(*)()); // the name of the function mf2 has C++ language
                // linkage; the parameter has type pointer to C function
    };
}

如果外部“C” block 中允许使用模板,则实例化的成员函数将具有 C++ 链接。

那么,为什么 C++98 标准的第 14 章"template"状态:

A template name may have linkage (3.5). A template, a template explicit specialization (14.7.3), and a class template partial specialization shall not have C linkage.

模板“可能”有链接是什么意思?什么是模板链接?

当一个类没问题并且模板实例化的所有成员函数(默认构造函数、析构函数和赋值运算符重载)都具有 C++ 链接时,为什么明确禁止具有 C 链接的模板?

最佳答案

模板不是实际代码,它们只是编译器在知道模板参数后如何生成代码的指南。因此,在您尝试使用它们之前,它们实际上并不存在。您不能提供与不存在的东西的链接。

关于c++ - 为什么模板不能在 extern "C" block 内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4877705/

相关文章:

c++ - 无法从 NULL 资源创建 RenderTargetView

c++ - STL multimap - 如何获取 multimap 中所有键值的列表

c++ - 继承默认模板值

c++ - "extern"关键字使用

C++将变量传递给类到函数

c++ - FastCV 腐 eclipse /膨胀参数

c++ - g++ 模板名称修改

c++ - 模板实例化 - 对某些类使用 C++11 的 sizeof...() 运算符时没有匹配函数

c++ - 在 c/c++ 中使用 extern 背后的概念是什么?

c++ - 外部错误 - undefined reference