I have the following class:
#pragma once
#include
#include
class testclass
{
public:
template T item(const s
The problem boils down to the common problem of not having the templates in the header file. The compiler, when processing main
does not see the specialization and it generates its own instantiation of the generic template for std::string
. This is a violation of the ODR, as there are now 2 different specializations for std::string
in the same program, but the compiler is not required to diagnose it.
The simple solution is to declare/define the specialization in the header so that the compiler can either use it, or at least will know not to generate the specialization from the generic version when processing main
Sadly, this is not the whole story. The explicit specialization of the member template function 'item' must be unique throughout the program. If you were to create another translation unit that implemented another function that did the same thing as 'main' and linked that into your program, you would get multiple definitions. You have a couple of alternatives: (1) declare the specialization to be an inline function in the header (not a general solution); (2) declare the specialization in the header and define it in the '.cpp' file (general answer). This is a great example of the importance of understanding at a fundamental level how compilers and linkers implement the "physical linking" of various C++ constructs.