-1

I'm having a problem when writing C++ templates, let's check the code:

abc.h

class ABC
{
public:
        template <class T>
        T getSomething(const std::string& name, ABC* owner = 0);
        ABC* getSomething(const std::string& name);
};

abc.cpp


#include "abc.h"

template <class T>
T ABC::getSomething(const std::string& name, ABC* owner)
{
        return dynamic_cast<T>(owner ? owner->getSomething(name) : getSomething(name));
}


ABC* ABC::getSomething(const std::string& name)
{
        return NULL;
}

and my main function will be like :

int main()
{
        ABC abc;
        ABC* test = abc.getSomething<ABC*>("hello", NULL);
}

when I put my main inside this abc.cpp and compile it, there is no problem everything works normal

but the problem comes when I use this abc.cpp (later I compiled it into abc.o) and then put my main function in different file (say, def.cpp).

I got really weird error, the error says :

/tmp/ccn1H4Bg.o: In function `main':
def.cpp:(.text+0x4a): undefined reference to `ABC* ABC::getSomething<ABC*>(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, ABC*)'
collect2: ld returned 1 exit status

could you all help me what I do wrong here?

Thanks Guys!

BobAlmond
  • 459
  • 5
  • 12

1 Answers1

2

this is because of the compiler does not support separate templates compiled. move the template code in abc.cpp to abc.h can solve this problem. like this:

//abc.h
class ABC
{
public:
        template <class T>
        T getSomething(const std::string& name, ABC* owner = 0);
        ABC* getSomething(const std::string& name);
};

template <class T>
T ABC::getSomething(const std::string& name, ABC* owner)
{
        return dynamic_cast<T>(owner ? owner->getSomething(name) : getSomething(name));
}

//abc.cpp
ABC* ABC::getSomething(const std::string& name)
{
        return NULL;
}

//def.cpp
int main()
{
        ABC abc;
        ABC* test = abc.getSomething<ABC*>("hello", NULL);
}
hahaya
  • 106
  • 1
  • 6