Hi!
I am trying to specialize a member function of a template class (see
code below).
The moment the header with the "template class definition" and
"template class member function specialization" is included in two
different translation units (cpp-files).
Problem:
g++ 3.3.3 (or more exact the ld linker 2.14.90.0.7) complains about
multiple definitions / multiple symbols with the same name...
Intels c++ compiler (icc 8.0) compiles the same code without any
problem and links it.
Am I doing something wrong (C++ in a Nutshell shows that code like mine
should work on page 194) or is this a compiler/linker problem?
Kind regards,
Bjoern
Code:
=====
template_class.hpp - contains the specialized template class member
function "type"
------------------------------------------------------------------------------------------------------------------
#ifndef
#ifndef INCLUDED_template_class_HPP
#define INCLUDED_template_class_HPP
template< typename T >
class template_class {
public:
int num() const;
};
template< typename T >
int
template_class<T>::num() const
{
return 0;
}
template<>
int
template_class<float>::num() const
{
return 42;
}
#endif // INCLUDED_template_class_HPP
main.cpp - uses the template class
-----------------------------------------------
#include <iostream>
#include "template_class.hpp"
#include "linker_tester.hpp"
int main (int argc, char * const argv[]) {
(void) argc; // Prevent parameter not used warning.
(void) argv; // Prevent parameter not used warning.
template_class< int > a;
template_class< float > b;
std::cout << "a.num() " << a.num() << std::endl;
std::cout << "b.num() " << b.num() << std::endl;
output();
return 0;
}
linker_tester.hpp - declares a simple function that uses the template class
---------------------------------------------------------------------------------------------------
#ifndef
#ifndef INCLUDED_linker_tester_HPP
#define INCLUDED_linker_tester_HPP
int output();
#endif // INCLUDED_linker_tester_HPP
linker_tester.cpp
----------------------
#include "linker_tester.hpp"
#include <iostream>
#include "template_class.hpp"
int output()
{
template_class< int > a;
template_class< float > b;
std::cout << "output a.num() " << a.num() << std::endl;
std::cout << "output b.num() " << b.num() << std::endl;
return 0;
}