C ++模板好友功能未链接 [英] C++ template friend function not linking

查看:50
本文介绍了C ++模板好友功能未链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下在VC6中编译的代码:

I have the following code which compiles in VC6 :

Text.h:

template <typename T>
class CTextT
{
   public:

    friend  CTextT add(const CTextT& text1, const CTextT& text2) ;

friend CTextT operator+(const CTextT& string1, const CTextT& string2)   
    {  
       return ::add(string1, string2);}
    }

    ....................
};

在标题的末尾

 #include "Text.inl"

Text.inl:

template <typename T>
CTextT<T> add(const CTextT<T>& text1, const CTextT<T>& text2) 
{   
    CTextT<T> temp ;

    // do something

    return temp ;
}

但是VC2010给我LINK错误:

But VC2010 gives me LINK error:

error LNK2019: unresolved external symbol "class CTextT<char> __cdecl add(class     CTextT<char> const &,class CTextT<char> const &)" (?add@@YA?AV?$CTextT@D@@ABV1@0@Z)  
referenced in function "class CTextT<char> __cdecl operator+(class CTextT<char> const &,class CTextT<char> const &)" (??H@YA?AV?$CTextT@D@@ABV0@0@Z)

 1>.\Debug\UnitTestText.exe : fatal error LNK1120: 1 unresolved externals

如果我将代码放在Text.h中,则可以正常编译.但是我不想这样做,因为我想使声明在执行时保持干净.我不知道为什么函数在类之外时链接器在这种情况下会抱怨?这是唯一的问题,该类很大,并且还有其他朋友函数返回CTextT.

If I place the code in the Text.h it compiles fine. But I do not want to do this because I want to keep declaration clean from implementation. I can't figure why linker is complaining in this case when the function is outside the class? This is the only problem and the class is very big and there are other friend functions returning CTextT.

推荐答案

解决方案如下:

template <typename T>
class CTextT
{
public:

template <typename T>
friend CTextT<T> add(CTextT<T> const&, CTextT<T> const&) ;

friend  CTextT<T> operator+(const CTextT<T>& string1, const CTextT<T>& string2)  
{  return ::add(string1, string2); }

};

template <typename T>
CTextT<T> add(CTextT<T> const&, CTextT<T> const&) 
{
   CTextT<T> temp ;
   return temp ;
}

我找到了以下指向MSDN的链接,解释了如何在模板中添加朋友功能- http://msdn.microsoft.com/en-us/library/f1b2td24.aspx .

I found the following link to MSDN explaining how to add friend functions in templates - http://msdn.microsoft.com/en-us/library/f1b2td24.aspx.

我进行了测试,它适用于VS2010和VS2012.VC6不需要第二个模板声明(它从类中获取),并且在VC6中,此代码将不再编译-将返回内部编译器错误.

I tested and it works for VS2010 and VS2012. VC6 does not need the second template declaration (it takes it from the class) and in VC6 this code will not compile anymore - will return INTERNAL COMPILER ERROR.

这篇关于C ++模板好友功能未链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆