The One Definition Rule states that a program should contain one definition of every non-inline function. For members of template classes, this not entirely clear to me:
///////////
// Tfoo.h
template<typename T> class A {
void foo(){}
};
///////////
// intfoo.h
#include <Tfoo.h>
template<> class Foo<int> {
void foo(); // declaration only
};
/*inline*/ void Foo<int>::foo(){} // definition
///////////
// X.cpp
#include <intfoo.h>
///////////
// Y.cpp
#include <intfoo.h>
In this case, both clientX.obj and clientY.obj have a definition of Foo<int>::foo
. The linker complains that this symbol is defined more than once:
Y.obj : error LNK2005: "private: void __thiscall Foo<int>::foo(void)"
(?foo@?$Foo@H@@AAEXXZ) already defined in X.obj
When I prepend inline
to the definition of Foo<int>::foo()
, all goes well and the linker is happy. Also when I define them the method in a separate compilation unit (e.g. intfoo.cpp).
(Note: this solution was suggested in https://mcmap.net/q/1479169/-how-to-provide-a-explicit-specialization-to-only-one-method-in-a-c-template-class)
Possibly a misconception, but aren't member functions of template classes always 'inline'? What is the rule here?