大佬教程收集整理的这篇文章主要介绍了C 11 extern模板:我们在哪里真正需要它们?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
在C 11中,我们有模板显式实例化声明(extern模板类Foo< int>),它应该阻止模板类的隐式实例化. (Class template instantiation)
我试图模拟我实际需要显式实例化声明的情况,以减少编译时间.但我不能.看起来一切都没有这个功能(或不能使用它).
这是一个例子:
//Foo.h #pragma once template<class T> class Foo { T inst; public: Foo(T i); T& get() const; }; //Foo.cpp #include "stdafx.h" #include "Foo.h" template<class T> Foo<T>::Foo(T inst) : inst(inst) { } template<class T> T& Foo<T>::get() const { return inst; } template class Foo<int>; //explicit instantiation deFinition //test1.h #pragma once #include "Foo.h" //This line does not work //extern template class Foo<int>; //explicit instantiation declaration. void baz(); //test1.cpp #include "stdafx.h" #include "test1.h" void baz() { Foo<int> foo(10); int i = foo.get(); }
结果不取决于我是否评论(extern模板类Foo< int> ;;)行. 这是* .obj文件的符号:
注意在test1.obj中标记为UNDEF的Foo< int> :: Foo< int>(int)和int Foo< int> :: get(void)const这意味着它们必须在别处解析(即Foo仅被编译)一旦).
ATTEMP#2:
如果我在Foo.h文件中定义完整模板(没有显式实例化定义),那么extern模板没有帮助 – 模板编译两次(在test1.cpp和test2.cpp中).
//test1.h #pragma once #include "Foo.h" void baz(); //test1.cpp #include "stdafx.h" #include "test1.h" void baz() { Foo<int> foo(10); //implicit instantiation of Foo<int> int i = foo.get(); } //test2.h #pragma once #include "Foo.h" extern template class Foo<int>; void bar(); //test2.cpp #include "stdafx.h" #include "test2.h" void bar() { Foo<int> foo(10); //should refer to Foo<int> from test1.obj but it is NOT int i = foo.get(); }
这是符号转储:
所以我的问题是显式实例化声明可能有用吗?或者我可能会在测试中遗漏一些东西?
我用的是VS2013编译器.
简而言之,当您在头文件中定义和实现模板时,编译器可能会内联它.然后它通过标准(14.7.2 / 10“显式实例化”)使显式实例化定义不起作用.
所以我们需要强制编译器不内联模板.例如,在声明之后实现它.
template<class T> class Foo { ... T get() const; }; template<class T> T Foo<T>::get() const { ... }
以上是大佬教程为你收集整理的C 11 extern模板:我们在哪里真正需要它们?全部内容,希望文章能够帮你解决C 11 extern模板:我们在哪里真正需要它们?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。