首页 > 解决方案 > 如何导出模板功能?

问题描述

从这篇文章中,我需要导出函数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

但是还是没有成功!我哪里做错了?如何修复我的代码?

标签: c++

解决方案


您不能从 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);


推荐阅读