Skip to main content
GameDev.net gamedev.net
🔒 Locked 🎮 Unity

Templates, Namespaces, Linking.

Started by Skarsha May 26, 2006 at 6:19 AM 1 replies 550+ views
Original Post
Skarsha
Skarsha
Hi I am trying to explicitly instantiate (is that the right way to say it?) a template inside a namespace.

// INSIDE GENERIC HEADER:

namespace zug {
    template <typename T> void foo(T &var);
}

template <typename T>
inline void bar(T var) {
    zug::foo(var);
}

// INSIDE OBJECT-SPECIFIC HEADER:

namespace zug {
    void foo(int &var);
}

// INSIDE OBJECT-SPECIFIC SOURCE:

void zug::foo(int &var) {}

// MAIN ROUTINE:

int main() {
    bar(1);
    return 0;
}

The above does not compile (in g++), but it is intended to. foo() is a template function that I want to explicitly instantiate for (in this example) int. bar() is a template function that calls the template function foo(). the function foo() is declared and defined with template parameter T as "int". bar() is called with template parameter T as "int", calling foo() also with T as "int". The error I get is: demo.cpp:(.gnu.linkonce.t._Z3barIiEvT_[void bar(int)]+0x10): undefined reference to `void zug::foo(int&)' If I remove the namespacing, it compiles fine. It also compiles fine if I declare the int version of foo before the template version. Can anyone see what is wrong with my syntax? Am I supposed to indicate somehow that my explicit instantiation of foo() is a template instantiation? All help appreciated.
rip-off
rip-off
I believe you must tell the compiler that you are using a template:

// headernamespace zug {    template<>    void foo(int &var);}//sourcetemplate<>void zug::foo(int &var) {}


Your code, as posted, had 2 different versions of foo,

foo<*>( * & ) and foo( int & )

whereas you wanted:

foo<*>( * & ) with foo( int & ) = { /*code */ }

Hope this helps.
Skarsha
Skarsha
Thanks, problem solved.

I'd never seen an empty template (template <>) before now.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.