Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a template method?

There are a lot of online documents explaining how to write template methods, but not much example about how to call them, how to use them in code.

I have a template method like this:

VectorConvertor.h

template <class T>
static void AppendToVector(std::vector<T> & VectorToBeAppended,
                           std::vector<T> & VectorToAppend);


VectorConvertor.cpp

template <class T>
void VectorConvertor::AppendToVector(std::vector<T> & VectorToBeAppended,
                                     std::vector<T> & VectorToAppend)
{
    for (std::vector::size_type i=0; i<VectorToAppend.size(); i++)
    {
        VectorToBeAppended.push_back(VectorToAppend.at(i));
    }
}

Usage attempt in code:

std::vector<uint8_t> InputData, OutputData;
// ...
VectorConvertor::AppendToVector(OutputData, InputData);


I compile this code without any error. But when I try to use this method I get the following errors:

error LNK1120: 1 unresolved externals

and

error LNK2019: unresolved external symbol "public: static void __cdecl VectorConvertor::AppendToVector(class std::vector > &,class std::vector > &)" (??$AppendToVector@E@VectorConvertor@@SAXAEAV?$vector@EV?$allocator@E@std@@@std@@0@Z) referenced in function "public: staticclass std::vector > __cdecl Utf8::WStringToUtf8(class std::basic_string,class std::allocator >)" (?WStringToUtf8@Utf8@@SA?AV?$vector@EV?$allocator@E@std@@@std@@V?$basic_string@_WU?$char_traits@_W@std@@V?$allocator@_W@2@@3@@Z)


When I don't use this method in my code I don't get any error messages. What am I doing wrong while calling it? Am I missing something?


I'm using Visual Studio 2010 Express Edition.

like image 426
hkBattousai Avatar asked Nov 24 '10 19:11

hkBattousai


1 Answers

In C++ you can't separate the definition in a .cpp file when using templates. You need to put the definition in the header file. See:

http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12

like image 169
Nathan S. Avatar answered Sep 17 '22 23:09

Nathan S.