template questions

Hi,

With the code below, the compiler is picking the wrong f() for one of the template instantiations. Depending on whether I build with:

g++ t1.cpp t2.cpp

or

g++ t2.cpp t1.cpp

It picks a 'different' wrong f().

I sort of get why it's happening, but it seems dangerous! Is this just a limitation of the way c++ templates work?

Bye,
Mark

'----- t1.cpp -----
#include <stdio.h>

extern void test();

namespace n1{
void f(){
puts( "f1" );
}
}
using namespace n1;

#include "t3.h"

int main(){
test();
List<int> t;
t.update();
}

'----- t2.cpp -----
#include <stdio.h>

void f(){
puts( "f2" );
}

#include "t3.h"

void test(){
List<int> t;
t.update();
}


'----- t3.h -----
template<class T> struct List{
void update(){
f();
}
};




This has nothing to do with templates. (I could be wrong from here on in) I think it is to do with the c++ linker. It's finding two definitions of struct List and using the first. The dangerous thing in your code is using namespace n1;
Last edited on
Topic archived. No new replies allowed.