Re: Separate Template Definition I wrote class Data in header. The C++ Compiler compiled without errors. I decided to move all member functions into source code because they are for implementation. I do not like that they are placed in class body.
Immortal Nephi <Immortal_Nephi@hotmail.com> writes:
I wrote class Data in header. The C++ Compiler compiled without
errors. I decided to move all member functions into source code
because they are for implementation. I do not like that they are
placed in class body.
I got error message:
Linking...
Main.obj : error LNK2001: unresolved external symbol "public:
__thiscall Data<unsigned char>::operator unsigned char(void)" (??B?
$Data@E@@QAEEXZ)
C:\Main.exe : fatal error LNK1120: 1 unresolved externals
Could be problem with member function cast operator. All other
member functions complied without any problems.
// Data.h
#if !defined(DATA_H )
#define DATA_H
template< typename T >
class Data {
public:
Data();
~Data();
operator unsigned char ();
private:
unsigned char x;
};
#endif // end macro !defined( DATA_H )
// Data.cpp
template< typename T >
Data< T >::Data() : x( 5 ) {}
template
Data< unsigned char >::Data();
template< typename T >
Data< T >::~Data() {}
template
Data< unsigned char >::~Data();
// Error unresolved linkage
template< typename T >
Data< T >::operator unsigned char () {
return x;
}
template
Data< unsigned char >::operator unsigned char ();
// main.cpp
int main() {
Data< unsigned char> data;
unsigned char x = data;
return 0;
}
Taking your code as is (adding only the relevant includes to Main.cpp
and Data.cpp), I can confirm the link failure with VC++ 2008 Express:
d:\CPPProjects\CLCPP>cl /EHsc Main.cpp Data.cpp
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01
for 80x86
Copyright (C) Microsoft Corporation. All rights reserved.
Main.cpp
Data.cpp
Generating Code...
Microsoft (R) Incremental Linker Version 9.00.30729.01
Copyright (C) Microsoft Corporation. All rights reserved.
/out:Main.exe
Main.obj
Data.obj
Main.obj : error LNK2019: unresolved external symbol "public:
__thiscall Data<unsigned char>::operator unsigned char(void)"
(??B?$Data@E@@QAEEXZ) referenced in function _main
Main.exe : fatal error LNK1120: 1 unresolved externals
d:\CPPProjects\CLCPP>
However, the same code seems to compile fine using gcc-4.4.3:
18:48:03 Paul Bibbings@JIJOU
/cygdrive/d/CPPProjects/CLCPP $i686-pc-cygwin-g++-4.4.3 -static
Main.cpp Data.cpp
18:48:49 Paul Bibbings@JIJOU
/cygdrive/d/CPPProjects/CLCPP $
so, there appears to be some difference of opinion between the two
compilers as to whether your code should work or not.
Regards
Paul Bibbings