0
// forward declarations
template<typename charType> class string;
template<typename charType> string<charType> operator + (const string<charType>&, const string<charType>&);
template<typename charType> string<charType> operator + (const string<charType>&, const char*);

class string {
...
friend string<charType> operator + <>(const string<charType>& str1, const string<charType>& str2);
friend string<charType> operator + <>(const string<charType>& str1, const char* str2);
}

Above you can see my current header file for my string class (I found this from another Answer on SO). How do you provide a correct definition for these declaritions?

// Operators
template <typename charType>
string<charType> operator+ (const string<charType>& str1, const string<charType>& str2)
{
    charType* tmp = new charType[str1._length + str2._length + 1];

    memcpy(tmp, str1._data, str1._length);
    memcpy(tmp + str1._length, str2._data, str2._length + 1);

    return string<charType>(tmp, str1._length + str2._length);
}

This leads to an unresolved external. (Presumably because the function header's dont match even when adding a <>)

I'm working on the newest Version of VS2017 (thus using microsoft's compiler). Taken from a comment: 'how to instantiate a particular template instance in a translation unit, so that the template instance can be resolved from other translation units where the template definition is not available.'

Swagov3rflow
  • 25
  • 1
  • 8
  • If you are defining the function in a .cpp file, move it to the .h file. See [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – R Sahu Nov 26 '17 at 00:02
  • @RSahu Implementation in the header file is infeasible for this specific application. Also it's possible to implement templated functions outside the header file, i'm just missing the correct declaration (I guess). – Swagov3rflow Nov 26 '17 at 00:12
  • what is the compiler saying? – Free Url Nov 26 '17 at 00:20
  • @Zroach unresolved external: class uap::string __cdecl uap::operator+(class uap::string const &, class uap::string const&) – Swagov3rflow Nov 26 '17 at 00:22
  • This is highly compiler-specific. You need to edit your question, spell out exactly which compiler you're using, and make it clear that your question is to how to instantiate a particular template instance in a translation unit, so that the template instance can be resolved from other translation units where the template definition is not available. – Sam Varshavchik Nov 26 '17 at 00:37
  • It seems you want to explicitly instantiate `operator+`. Add this line to your source file: `template string operator+ (const string& str1, const string& str2);` – Igor Tandetnik Nov 26 '17 at 02:05

0 Answers0