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

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

问题描述

假设我有 fileA.h ,它用模板函数声明一个类 classA SomeFunc ; T>()。这个函数直接在头文件中实现(和模板函数一样)。现在我添加 SomeFunc()(像 SomeFunc< int>() $ c> fileA.C (即不在头文件中)。



如果我现在调用 SomeFunc< int>()从一些其他代码(也可能从另一个库),它会调用泛型版本还是专业化?



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

解决方案

专门化在呼叫点不可见的模板。不幸的是,编译器不需要诊断这个错误,然后可以做他们喜欢的代码(在标准语言是形成,无需诊断)。



技术上,您需要在头文件中定义特殊化,但是每个编译器都会按照您的预期处理这个问题:这是在C ++ 11中使用新的extern模板工具来修复的:

  extern模板<> SomeFunc< int>(); 

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


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).

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

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").

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>();

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天全站免登陆