Binding error in C ++ template

I need to create a simple Logger (without third-party libraries), which should be a link to the dll. So I generated a class with some of its class methods - these are templates, the code compiles fine, but I get a linker error. I am compiling with MS VS 2008 and gcc-4. The code:

Class Log.h:

class MiniLogger
{
private:
   std::ofstream mOutPutFile;
protected:
   void write (std::string const& text);
public:
   ~MiniLogger();
   MiniLogger( std::string const& lName) throw(FileError);
   static MiniLogger* getInstance(std::string const & fName);
   static void destoryInstance(MiniLogger*);

  template<class T>
  MiniLogger& operator<<(T & data);
  MiniLogger& operator<<(std::ostream& (*func)(std::ostream&) );

};


MiniLogger& MiniLogger::operator<< (std::ostream& (*func)(std::ostream&))
{

   //mOutPutFile << out;
   return *this;
}
template<class T>
MiniLogger& MiniLogger::operator<< (T  & data)
{
 //Just try with out calling other method
// write(data);
   return *this;
}

I basically created an Object and used it:

#include "log.h"

int main()
{


    MiniLogger &a=*(MiniLogger::getInstance("text.txt"));

    a << "text" << std::endl;


return 0;
}

I get

@ubu11-10-64b-01:~/cplus/template$ g++ main.cpp log.cpp
/tmp/cccMdSBI.o: In function `MiniLogger::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))':
log.cpp:(.text+0x0): multiple definition of `MiniLogger::operator<<(std::basic_ostream<char, std::char_traits<char> >& (*)(std::basic_ostream<char, std::char_traits<char> >&))'
/tmp/ccj3dfhR.o:main.cpp:(.text+0x0): first defined here
+3
source share
1 answer

You have defined a function in the header file. Since this header file is included in several translation units (namely, main.cpp and log.cpp), you multiplied a specific function. (See One Rule of Definition .)

inline extern .

: MiniLogger& MiniLogger::operator<< (std::ostream& (*func)(std::ostream&)).

№ 1:

// Log.h
inline
MiniLogger& MiniLogger::operator<< (std::ostream& (*func)(std::ostream&))
{
 //mOutPutFile << out;
 return *this;
}

№ 2:

// Log.h
extern
MiniLogger& MiniLogger::operator<< (std::ostream& (*func)(std::ostream&));

// Log.cpp
MiniLogger& MiniLogger::operator<< (std::ostream& (*func)(std::ostream&))
{
 //mOutPutFile << out;
 return *this;

}


. , template<class T> MiniLogger& MiniLogger::operator<< (T & data) - , . , , . ( .)
+4

All Articles