Member template specialization and scope

It seems to me that C ++ does not allow element template specialization in any area other than the namespace and global area (MS VSC ++ Error C3412). But for me it makes sense to specialize the base template of the base class in a derived class, because this is what the derived classes do - specialize things in the base class. For example, consider the following example:

struct Base { template <class T> struct Kind { typedef T type; }; }; struct Derived : public Base { /* Not Allowed */ using Base::Kind; template <> struct Kind <float> { typedef double type; }; }; int main(void) { Base::Kind<float>::type f; // float type desired Derived::Kind<float>::type i; // double type desired but does not work. } 

My question is: why is this not allowed?

+4
source share
3 answers

I get what you are trying to do, but you are not doing it right. Try the following:

 struct Base{}; struct Derived{}; // Original definition of Kind // Will yield an error if Kind is not used properly template<typename WhatToDo, typename T> struct Kind { }; // definition of Kind for Base selector template<typename T> struct Kind<Base, T> { typedef T type; }; // Here is the inheritance you wanted template<typename T> struct Kind<Derived, T> : Kind<Base, T> { }; // ... and the specialization for float template<> struct Kind<Derived, float> { typedef double type; }; 
+4
source

My question is: why is this not allowed?

From my copy of the project it can be seen that the following sets the specified restriction:

In an explicit declaration of specialization for a class template, a member of a class template, or a member of the class template, the name of the class that is explicitly specialized should be a simple identifier template.

The workaround is to specialize the enclosing class.

+1
source

I will ignore the standard specifications and try a boolean argument:

If you have two classes:

 class A { struct S { }; }; class B: public A { struct S { }; }; 

A :: S and B :: S are two different types. Expanding logic to specialized patterns when you try to specialize an inner class declared in a base class through an inner class in a derived class, you are actually trying to define a different type with the same name (but with a different namespace).

+1
source

All Articles