Tuesday 15 July 2014

c++ - Linker Error for templated Class with friend functions -



c++ - Linker Error for templated Class with friend functions -

i'm trying recreat stack forward_list. however, utilize friend functions overload + , << operator.

#pragma 1 time #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 friend functions linker error , when seek phone call them in main like:

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

and these 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.

your template friend declarations within stack class not quite correct. need declare 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 using msvc, please see this microsoft documentation farther reference.

c++ visual-studio-2012 c++11 friend

No comments:

Post a Comment