C++ template friend function not linking

前端 未结 2 1544
轻奢々
轻奢々 2021-01-27 01:52

I have the following code which compiles in VC6 :

Text.h:

template 
class CTextT
{
   public:

    friend  CTextT add(const CTextT&         


        
相关标签:
2条回答
  • 2021-01-27 02:40

    The solution is following:

    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 ;
    }
    

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

    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.

    0 讨论(0)
  • 2021-01-27 02:42

    Of course it does give a linker error. The add() function you made a friend isn't a function template! It is a non-template function declared inside a class template. As a result, you won't be able to define this function as a template, either. You can directly define it at the friend declaration.

    The alternative is to declare the function template prior to the class template. Of course, this requires a declaration of the class template, too. The following should work:

    template <typename T> class CTextT;
    template <typename T> CTextT<T> add(CTextT<T> const&, CTextT<T> const&);
    template <typename T>
    class CTextT
    {
        friend CTextT<T> add<>(CTextT<T> const&, CTextT<T> const&);
        // ...
    };
    

    Now the template definition you have give should work.

    0 讨论(0)
提交回复
热议问题