什么时候使用模板显式实例化? [英] When would you use template explicit instantiation?
本文介绍了什么时候使用模板显式实例化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚刚阅读了关于模板显式实例化:
template struct MyStruct< long> ;;
/ p>
它被描述为相当少见,因此在什么情况下它会有用?
解决方案
其中一个用例是隐藏最终用户的定义。
tpl.h :
template< typename T>
void func(); // Declaration
tpl.cpp :
template< typename T>
void func()
{
//定义
}
template void func< int>(); //显式实例化int
template void func< double>(); // double double的显式实例化
main.cpp b
$ b
#includetpl.h
int main()
{
func< double>(); // OK
func< int>(); // OK
// func< char>(); - 链接错误
}
I've just been reading about template explicit instantiation:
template struct MyStruct<long>;
It was described as "quite rare", so under what circumstances would it be useful?
解决方案
One of the use cases is to hide definitions from the end-user.
tpl.h:
template<typename T>
void func(); // Declaration
tpl.cpp:
template<typename T>
void func()
{
// Definition
}
template void func<int>(); // explicit instantiation for int
template void func<double>(); // explicit instantiation for double
main.cpp
#include "tpl.h"
int main()
{
func<double>(); // OK
func<int>(); // OK
// func<char>(); - Linking ERROR
}
这篇关于什么时候使用模板显式实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文