Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do templates specialisations need to be inlined?

I am referring to this answer:

https://stackoverflow.com/a/4447057/930315

I ran into a similar issue as the OP of the cited question, having a function

template<typename T>
void func(T& val);

and its specialization

template<>
void func<mytype>(mytype& val);

resulted in a duplicate symbols linker error (the methods are implemented in a '.tpp' file that is included at the end of my header). adding inline to the specialised function resolved the issue. Why?

like image 782
Faser Avatar asked Jan 23 '18 13:01

Faser


1 Answers

Well, if you want the standard quote on this, that'd be over at [temp.expl.spec]/12

An explicit specialization of a function or variable template is inline only if it is declared with the inline specifier or defined as deleted, and independently of whether its function or variable template is inline. [ Example:

template<class T> void f(T) { /* ... */ }
template<class T> inline T g(T) { /* ... */ }

template<> inline void f<>(int) { /* ... */ }   // OK: inline
template<> int g<>(int) { /* ... */ }           // OK: not inline 

— end example ]

That's why you have to do it. It's independent because I believe doing otherwise would be needlessly restrictive, as Yola demonstrated.

like image 112
StoryTeller - Unslander Monica Avatar answered Sep 28 '22 16:09

StoryTeller - Unslander Monica