Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Definition of a class member in the primary template and an implicit instantiation during specialization

I have the following example that I've decomposed from §14.7.3/6 [temp.expl.spec] that defines a class member enumeration in the primary template and subsequently specializes it. The following doesn't compile in clang:

template<class T>
struct A {
    enum E : T;
};

template<class T>
enum A<T>::E : T { eT };

template<>
enum A<char>::E : char { echar }; // ill-formed, A<char>::E was instantiated
                                  // when A<char> was instantiated

// error: explicit specialization of 'E' after instantiation

The reason is supposed to be that the definition of the unscoped member enumeration was instantiated before the specialization. 14.7.1 [temp.inst]/1:

The implicit instantiation of a class template specialization causes the implicit instantiation of [...] the definitions of unscoped member enumerations and member anonymous unions.

I'm trying to understand why that is a problem exactly. Is it because if the enumeration already has a definition, then that would cause a redefinition error during the specialization?

like image 299
David G Avatar asked Aug 17 '14 17:08

David G


People also ask

What is implicit instantiation?

Implicit instantiation means that the compiler automatically generates the concrete function or class for the provided template arguments. In general, the compiler also deduces the template arguments from the function's arguments. In C++17, the compiler can also deduce the template arguments for class templates.

What is the instantiation of the class template?

The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation.

What is explicit template specialization?

Explicit (full) specializationAllows customizing the template code for a given set of template arguments.

What is the syntax for explicit class specialization?

What is the syntax to use explicit class specialization? Explanation: The class specialization is creation of explicit specialization of a generic class. We have to use template<> constructor for this to work. It works in the same way as with explicit function specialization.


1 Answers

you need to specialize for the whole class definition:

template<class T>
struct A {
  enum E : T { eT };
};

template<>
struct A<char> {
  enum E : char { echar };
};
like image 113
DU Jiaen Avatar answered Sep 19 '22 13:09

DU Jiaen