1. Your operator= should take a const reference, as the compiler will attempt to generate one for you.
2. Your template definition will need to be available to all compiled units. The easiest way to do this is to make it inline and move it to a header file. Another way to do it is force your library (or program) to include a pre-instantiated copy. This is how your standard C++ library makes std::string and std::wstring available.
I couldn't find any links on this, I find that amazing!
Anyway, here's an example I knocked up. Number is a simple template class with a couple of methods, and we declare a couple of instances of this class. The impementation is in a seperate compiled unit, where the template implementation resides and a couple of instances are created (for int and double).
main() comes along and uses the code, seeing only the header and hopes the linker can sort it all out. The linker uses the instantiated int version, but can't find a long instantiation and generates an error.
The catch is that you can use this in libraries. That is how sting and wstring are instances of basic_string but still manage to be exported as code.
x.hpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
template <class T>
class Number
{
public:
Number(const T& n);
T get_value() const;
private:
T value;
};
#ifndef CREATE_INSTANCE
externtemplateclass Number<int>;
externtemplateclass Number<double>;
#endif
Sure - they are typedefs for a basic_string instantiated on a char.
But somewhere there has to be a compiled version of the non-inlined methods on basic_string -- and that is in the c++ runtime library.
Ok, I've edited the x.hpp and x.cpp by adding CREATE_INSTANCE for MSVC support.
Under MSVC:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
C:\cygwin\tmp>cl xmain.cpp x.cpp
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86
Copyright (C) Microsoft Corporation. All rights reserved.
xmain.cpp
x.cpp
Generating Code...
Microsoft (R) Incremental Linker Version 8.00.50727.762
Copyright (C) Microsoft Corporation. All rights reserved.
/out:xmain.exe
xmain.obj
x.obj
xmain.obj : error LNK2019: unresolved external symbol "public: __thiscall Number<long>::Number<long>(long const &
QAE@ABJ@Z) referenced in function _main
xmain.exe : fatal error LNK1120: 1 unresolved externals
Under g++
1 2 3 4
$ g++ xmain.cpp x.cpp -o x
/cygdrive/c/DOCUME~1/TEMP/LOCALS~1/Temp/ccmDRJdM.o:xmain.cpp:(.text+0x58): undefined reference to `Number<long>::
Number(longconst&)'
collect2: ld returned 1 exit status