且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么时候使用模板显式实例化?

更新时间:2023-10-09 22:11:40

其中一个用例是隐藏最终用户的定义。



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
}