The following bit of code fails to compile on gcc 4.5.3
struct Frobnigator { template<typename T> void foo(); template<typename T> void bar(); }; template<typename T> void Frobnigator::bar() { } template<typename T> void Frobnigator::foo() { bar<T>(); } template<> // error void Frobnigator::foo<bool>() { bar<bool>(); } template<> void Frobnigator::bar<bool>() { } int main() { }
Error message: specialization of ‘void Frobnigator::bar() [with T = bool]’ after instantiation
. I finally resolved this problem by having the specialization of Frobnigator::bar<bool>()
appear before Frobnigator::foo<bool>()
. Clearly the order in which the methods appear matter.
Why then is the following lite version of the above code, in which the the specialization of bar
appears after the generic version, valid ?
struct Frobnigator { template<typename T> void foo(); }; template<typename T> void Frobnigator::bar() { } template<> void Frobnigator::bar<bool>() { } int main() { }
To do so, we can use a function template specialization (sometimes called a full or explicit function template specialization) to create a specialized version of the print() function for type double.
Explicit (full) specializationAllows customizing the template code for a given set of template arguments.
You may define a template member function outside of its class template definition. When you call a member function of a class template specialization, the compiler will use the template arguments that you used to generate the class template.
Your first code is not correct by standard.
n3376 14.7.3/6
If a template, a member template or a member of a class template is explicitly specialized then that specialization shall be declared before the first use of that specialization that would cause an implicit instantiation to take place, in every translation unit in which such a use occurs; no diagnostic is required.
In your case - implicit instantiation of bar
function with type bool
is required by its usage in foo<bool>
, before explicit specialization declaration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With