在模板声明头中定义 extern 模板特化

问题描述

我有一个非常通用的模板函数,我只想在库中实例化一次以避免不必要的代码编译。为此,我想在声明主模板的标头中使用 extern template,这样包括标头在内的每个翻译单元都不会实例化模板。例如:

// ******** test.h ******* 
#include <iostream>

template <typename T>
void f(T t){
    std::cout << t << std::endl;
}

extern template void f<int>(int t);    



// ******** test.cpp ******* 
#include "test.h"

template<>
   void f<int>(int t){
}

template void f<int>(int t);

用 g++ 编译我得到这个错误:

$ g++ test.cpp
test.cpp:4:18: error: specialization of 'void f(T) [with T = int]' after instantiation
    4 | void f<int>(int t){
      |                  ^

如果我从头文件中删除 extern template 代码编译正常。我不清楚错误在哪里,也不知道如何最终修复它。

在此先感谢您的帮助。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...