Search code examples
c++visual-studio-2012c++11friend

Linker Error for templated Class with friend functions


I'm trying to recreat a stack with a forward_list. However, i use friend functions to overload the + and << operator.

#pragma once
#include <forward_list>
template <class T> class Stack;

template <class T>
Stack<T> operator+(const Stack<T> &a, const Stack<T> &b){
//implementation
}

template <class T>
std::ostream &operator<<(std::ostream &output, Stack<T> &s)
{
//implementation
}

template <class T>
class Stack
{
friend Stack<T> operator+(const Stack<T> &a, const Stack<T> &b);
friend std::ostream &operator<<(std::ostream &output, Stack<T> &s);
std::forward_list<T> l;
public:
//Some public functions
};

For both of the friend functions i get an linker Error , when i try to call them in my main like:

int main(){
  Stack<int> st;
  st.push(4);
  Stack<int> st2;
  st2.push(8);
  cout<<st + st2<<endl;
  return 0;
}

And these are the errors:

 error LNK2019: unresolved external symbol "class Stack<int> __cdecl operator+(class Stack<int> const &,class Stack<int> const &)" (??H@YA?AV?$Stack@H@@ABV0@0@Z) referenced in function _main
 error LNK2019: unresolved external symbol "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class Stack<int> &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@AAV?$Stack@H@@@Z) referenced in function _main

Thanks in advance.


Solution

  • Your template friend declarations within the Stack class are not quite correct. You need to declare like this:

    template<class T>
    friend Stack<T> operator+(const Stack<T> &a, const Stack<T> &b);
    
    template<class T>
    friend std::ostream &operator<<(std::ostream &output, Stack<T> &s);
    

    Since you are using MSVC, please see this Microsoft documentation for further reference.