简体   繁体   English

如何在C ++中实例化模板

[英]How to instantiate the template in C++

I want to export template functions from DLL. 我想从DLL导出模板函数 I know I can use template specialization method as following. 我知道我可以使用模板专业化方法如下。
func.hpp func.hpp
/*declare*/
template<typename T> DLL_EXPORTS T func(T para);
/*specialization*/
template<> DLL_EXPORTS int func<int>(int para);

func.cpp func.cpp
template<> DLL_EXPORTS int func<int>(int para)
{return para;}

If I use template specialization. 如果我使用模板专业化。 I should rewrite the func code for every type. 我应该为每种类型重写func代码。 It's not a good solution. 这不是一个好的解决方案。 But this is the only way I can found from the C++ Primer . 但这是我从C++ Primer找到的唯一方法。
I found another way occasionally from someone else's codes, as following. 我偶尔会从其他人的代码中找到另一种方法,如下所示。

func.hpp func.hpp
/*declare*/
template<typename T> DLL_EXPORTS T func(T para);

func.cpp func.cpp
template<typename T> DLL_EXPORTS T func (T para)
{return para;}

/*Instantiation*/
template DLL_EXPORTS int func<int>(int);
He use template DLL_EXPORTS int func<int>(int) to instantiate the template. 他使用template DLL_EXPORTS int func<int>(int)来实例化模板。 you can't add <> after the keyword template . 您无法在关键字template后添加<> This way also works on class template. 这种方式也适用于类模板。

My question : I can't find the way in the book. 我的问题 :我在书中找不到方法。 So I'm afraid that it'll not work sometimes. 所以我担心它有时不起作用。 Is it supported by the C++ standard? 它是否受C ++标准支持?

Yes, it called explicit instantiation See 14.7.2 of the C++11 standard (sorry I have no C++03 nearby). 是的,它称为显式实例化参见C ++ 11标准的14.7.2(抱歉,我附近没有C ++ 03)。

You may instantiate in your translation unit as much as you wish instances of your template w/ any types you want, and this code will be placed into your DLL. 您可以在翻译单元中实例化您希望模板的实例与您想要的任何类型,并且此代码将被放入您的DLL中。 And everything else just wouldn't. 其他一切都不会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM