0

I first implement following functions in the same .cpp file as the main(). Everything works perfectly. But I met some problem when I tried to define them in a header file and implement them in a separate .cpp file.

These are my original code:

template <class T> //implement the sum function of one single container
double sum(const T& source){...}

//explicit specialization for map
template<>
double sum<map<string, double>>(const map<string,double>& source){...}

template <class T> //implement the sum function for two iterators
double sum( const class T::const_iterator& start,  const class T::const_iterator& end){...}

//explicit specialization for map (sum function of iterator)
template<>
double sum<map<string, double>>(const map<string, double>::const_iterator& start,const map<string, double>::const_iterator& end){...}

void main(){...}

Then I remove the implementation of the functions and define them in a header file:

template <class T> //implement the sum function of one single container
double sum(const T& source);

//explicit specialization for map
template<>
double sum<map<string, double>>(const map<string,double>& source);

template <class T> //implement the sum function for two iterators
double sum( const class T::const_iterator& start,  const class T::const_iterator& end);

//explicit specialization for map (sum function of iterator)
template<>
double sum<map<string, double>>(const map<string, double>::const_iterator& start,const map<string, double>::const_iterator& end);

and implement them in a .cpp file.

Then when I include both of the header file and cpp file, and run the project:

main(){...}

I received error message like:

sum.obj : error LNK2005: "double __cdecl sum<class std::map<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >....

Can anyone give a hint what I might have done wrong?

Many thanks!

Holt
  • 36,600
  • 7
  • 92
  • 139
yxw
  • 133
  • 1
  • 8
  • Look over there ===> right side of this page under the Related heading. "Why can templates only be implemented in the header file?" tells you everything you need to know. – Hans Passant Mar 17 '15 at 17:05

1 Answers1

0

I think this is your problem:

double sum<map<string, double>> # <-- here

Seems that you are using the ">>" operator, you should give space for avoid that

double sum< map<string, double> > # space
Joel
  • 1,805
  • 1
  • 22
  • 22
  • No, it is allowed to do that since C++11. –  Mar 17 '15 at 17:05
  • I didn't see the C++11 tag – Joel Mar 17 '15 at 17:09
  • 1
    Actually, I think that the C++11 tag is made for specific problems with C++11, not C++ in general. Also this is a linker error, not compiler error - if it would be the problem with >> interpreted as bit shift operator, it would be a compiler error. –  Mar 17 '15 at 17:13