Explicit specialization of static function
I am using c++. I am using gcc and msvc 2019. I have static template function(non -class function). I want to explicitly specify the function like this:
template<class T, class Self>
static inline T Convert(Self self)
{
return T(self);
}
template<>
static inline int Convert<int>(std::string self)
{
return self.size();
}
It is compiling on msvc and not on gcc. On gcc the error is : explicit template specialization cannot have a storage class. What is the reason and how can I fix it. Why there is a difference between the compilers.
Solution 1:
Explicit specializations are not allowed to use storage class specifiers, such as static
.
But they also do not introduce new names. Therefore I don't think it has any meaning to try to make them static
. They should have the same linkage as the primary template.
But it is also unusual that you use static
and inline
on the primary template. Templates already practically behave like inline
functions and there is usually no reason to give them internal linkage, except if you rely e.g. on the instantiations having different function addresses in different translation units or that local static variables differ between translation units.