为什么模板不能在外部“C”块中?

新手上路,请多包涵

这是对 Is it possible to typedef a pointer-to-extern-“C”-function type 在模板的答案 的后续问题吗?

此代码无法使用 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 节,链接规范指出:

对于类成员的名称和类成员函数的成员函数类型,AC 语言链接被忽略。

它甚至给出了例子:

 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”块中允许模板,则实例化的成员函数将具有 C++ 链接。

那么,为什么 C++98 标准的第 14 章,模板指出:

模板名称可能具有链接 (3.5)。模板、模板显式特化 (14.7.3) 和类模板部分特化不应具有 C 链接。

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

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

原文由 Daniel Trebbien 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 940
2 个回答

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

所有名称要么具有外部链接、内部链接,要么没有链接(C++03 §3.5p2),但这与语言链接不同。 (令人困惑,我知道。C++0x 也通过链接改变了很多事情。)任何用作模板参数的东西都需要外部链接:

 void f() {
  struct S {};
  vector<S> v;  // Not allowed as S has internal linkage.
}

请注意,C++98 在您引用 §14p4 的内容中有“可能”,但 C++03 删除了“可能”,因为模板不能在会给它们内部链接的上下文中声明:

 void f() {
  // Not allowed:
  template<class T>
  struct S {};
}

原文由 Fred Nurk 发布,翻译遵循 CC BY-SA 2.5 许可协议

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

原文由 Mark Ransom 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏