c++ - 如何导出模板功能?
问题描述
从这篇文章中,我需要导出函数ci_find_substr
,所以在我的头文件中,我声明了函数:
template<typename Twst>
__declspec(dllexport) int ci_find_substr (const Twst& str1,const Twst& str2 ,
const std::locale& loc = std::locale());
但是当从另一个项目编译这段代码时:
int k=ci_find_substr (wstring(mycstring), wstring(L".doc");
我收到错误严重性代码描述项目文件行抑制状态
错误 LNK2001 无法解析的外部符号“int __cdecl ci_find_substr (class std::basic_string<wchar_t,struct std::char_traits<wchar_t>,class std::allocator<wchar_t> >,class std::basic_string<wchar_t,struct std::char_traits <wchar_t>,class std::allocator<wchar_t> >,class std::locale const &)" (?ci_find_substr @@YAHV?$basic_string@_WU?$char_traits@_W@std@@V?
我也在这篇文章中尝试了同样的事情
template<typename Twst>
int ci_find_substr (const Twst& str1,const Twst& str2,
const std::locale& loc = std::locale());
__declspec(dllexport) int ci_find_substr (const wstring& str1,const wstring& str2,
const std::locale& loc = std::locale()); // Explicit instantiation
但是还是没有成功!我哪里做错了?如何修复我的代码?
解决方案
您不能从 DLL 导出模板,您只能导出所述模板的特化!
#ifdef COMPILING_DLL
// ensure you are declaring 'COMPILING_DLL' somewhen when building your DLL
#define DLL_EXPORT __declspec(dllexport)
#else
// when using the function it must be DLL import!
#define DLL_EXPORT __declspec(dllimport)
#endif
// header
template<typename Twst>
DLL_EXPORT int ci_find_substr (const Twst& str1,const Twst& str2 ,
const std::locale& loc = std::locale());
// in the source file...
//
// |-- 'template'
// | specialisation type--|
// | |-- DLLEXPORT |
// V V V
template DLL_EXPORT int ci_find_substr<std::wstring>(
const std::wstring& str1,
const std::wstring& str2,
const std::locale& loc);
推荐阅读
- c# - 启用列加密 Azure Function App v2 错误
- swift - 为什么列表中带有导航链接的项目变成蓝色?
- c++ - 如果我的容器介于两个现有值之间,那么捏造迭代器类别是否合理?
- javascript - 使用 JavaScript 确定 div 中的中间 div
- flask-sqlalchemy - 为什么此 Flask 页面不会呈现并显示 500 错误?
- java - 在 Java Spring MVC 中使用 hashmap 作为数据库
- java - @Autowired 字段在测试中始终为空,我错过了什么?
- angular - 获取“调用者”、“被调用者”和“参数”属性可能无法在严格模式函数上访问,以便在 Function.invokeGetter 调用它们
- list - 将列表转换为嵌套元组 Haskell
- android - 从协程调用 ion 客户端时出现“无接口方法 setCallback”错误