C++ 函数模板特化的可见性 [英] Visibility of template specialization of C++ function

查看:38
本文介绍了C++ 函数模板特化的可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 fileA.h,它使用模板函数 SomeFunc<T>() 声明了一个类 classA.该函数直接在头文件中实现(与模板函数一样).现在我在 fileA.C (即不在头文件).

Suppose I have fileA.h which declares a class classA with template function SomeFunc<T>(). This function is implemented directly in the header file (as is usual for template functions). Now I add a specialized implementation of SomeFunc() (like for SomeFunc<int>()) in fileA.C (ie. not in the header file).

如果我现在从其他代码(可能也来自其他库)调用 SomeFunc<int>(),它会调用通用版本还是专业化版本?

If I now call SomeFunc<int>() from some other code (maybe also from another library), would it call the generic version, or the specialization?

我现在有这个问题,类和函数存在于一个库中,由两个应用程序使用.一个应用程序正确地使用了专业化,而另一个应用程序使用了通用形式(这会导致稍后出现运行时问题).为什么有区别?这可能与链接器选项等有关吗?这是在 Linux 上,使用 g++ 4.1.2.

I have this problem right now, where the class and function live in a library which is used by two applications. And one application correctly uses the specialization, while another app uses the generic form (which causes runtime problems later on). Why the difference? Could this be related to linker options etc? This is on Linux, with g++ 4.1.2.

推荐答案

对在调用点不可见的模板进行特化是错误.不幸的是,编译器不需要诊断这个错误,然后可以对你的代码做他们喜欢的事情(在标准中它是格式错误,不需要诊断").

It is an error to have a specialization for a template which is not visible at the point of call. Unfortunately, compilers are not required to diagnose this error, and can then do what they like with your code (in standardese it is "ill formed, no diagnostic required").

从技术上讲,您需要在头文件中定义特化,但几乎每个编译器都会按照您的预期处理这个问题:这在 C++11 中通过新的外部模板"工具得到了修复:

Technically, you need to define the specialization in the header file, but just about every compiler will handle this as you might expect: this is fixed in C++11 with the new "extern template" facility:

extern template<> SomeFunc<int>();

这明确地声明了特定的专业化是在别处定义的.许多编译器已经支持这一点,有些有,有些没有 extern.

This explicitly declares that the particular specialization is defined elsewhere. Many compilers support this already, some with and some without the extern.

这篇关于C++ 函数模板特化的可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆