Thread: Templated function (declaration and definition)

  1. #1
    I lurk
    Join Date
    Aug 2002

    Templated function (declaration and definition)

    I have a teplated function prototype in a header file, and the function definition in the source file.
    Header file
    template<class T>
    int ErrorBox(const T& msg, HWND hWnd = HWND_DESKTOP);
    Source file
    template<class T>
    int ErrorBox(const T& msg, HWND hWnd/* = HWND_DESKTOP*/)
    	tstringstream ss;
    	ss << msg;
    	return MessageBox(hWnd, ss.str().c_str(), _T("Error!"), MB_OK | MB_ICONERROR);
    Including the header file, and linking to the source file... whenever I try to call this function from main I get a linker error. What am I doing wrong?

  2. #2
    Registered User
    Join Date
    Jan 2003
    I don't feel like looking at the error and stuff but when I get gay errors, I just restart and things start working again. Dunno why.

  3. #3
    Programming Sex-God Polymorphic OOP's Avatar
    Join Date
    Nov 2002
    you can't put the template definition in a source file (well, unless you export, but your compiler doesn't support that )

    The reason why is that template definitions are recreated for each templatization because one module can't predict all templatizations -- it would even have to account for all datatypes it may not even know about. In order to be able to "make" new versions of the template functions, the source files have to have access to the template definitions. In turn, that means you have to include the template definition in the header file as opposed to the source file, otherwise you will not be able to work with it in a multi-file environment. You also don't have to worry about multiple definitions that you would have if you included the definition of a nontemplated function -- this is all handled for you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Errors including <windows.h>
    By jw232 in forum Windows Programming
    Replies: 4
    Last Post: 07-29-2008, 01:29 PM
  2. Quantum Random Bit Generator
    By shawnt in forum C++ Programming
    Replies: 62
    Last Post: 06-18-2008, 10:17 AM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  4. Errors with including winsock 2 lib
    By gamingdl'er in forum C++ Programming
    Replies: 3
    Last Post: 12-05-2005, 08:13 PM
  5. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM