template, specialization and header

T

Thibault

Hello,

I'm writing a generic class in c++ with templates ; I
wish to specialize one of its function. All the code is
in the header file, with the #ifndef/#endif macro to
avoid multiple inclusion of the header. But when i
include my header in other files (so more than one
include), the linker complaints about the specialized
function already defined in each file (error LNK2005).
Why ???

Here is the example code :

in test.h :

#ifndef _TEST_
#define -TEST_

#include <iostream>

template <class T>
class test
{
public:
test() {};
void print();
};

template <class T>
void test<T>::print()
{ cout << "hello" << endl; }

template <>
void test<int>::print()
{ cout << "hello int" << endl; }



in main.cpp :

#include "test.h"
#include "test2.h"

void main()
{
test<char> a;
a.print();
test<int> b;
b.print();
}



in test2.h

#include "test.h"
 
C

Carl Daniel [VC++ MVP]

Thibault said:
Hello,

I'm writing a generic class in c++ with templates ; I
wish to specialize one of its function. All the code is
in the header file, with the #ifndef/#endif macro to
avoid multiple inclusion of the header. But when i
include my header in other files (so more than one
include), the linker complaints about the specialized
function already defined in each file (error LNK2005).
Why ???

Because an explicit specialization of a template function is not itself a
template. It's an ordinary function whose name is a template-id, in
standardese. If you want to have an explicit specialization be inline, you
need to say so:

template <class T>
void test<T>::print()
{ cout << "hello" << endl; }

template <>
inline void test<int>::print()
{ cout << "hello int" << endl; }

HTH

-cd
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top