Using typedef in creating a template and declaring an extern template

There are two cases where typedef confuses me when it comes to extern template declaration and explicit template instantiation .

To illustrate these two, see below 2 snippets of code.

Consider the following example (case 1) :

 // suppose following code in some cpp file template <typename T> struct example { T value; }; // valid typedefs typedef example<int> int_example; typedef example<std::string> string_example; // explicit instantiation using above typedefs template class int_example; // -> compile time error template class string_example; // -> compile time error // instead we need to use type names template class example<int>; // -> OK template class example<std::string>; // -> OK // QUESTION 1: Why does this work however? is this valid code? typedef std::string type_string; template class example<type_string>; 

Why template class example<type_string> work with typedef? and why is it valid while template class string_example not?

Consider the following example (case 2) :

 // suppose following code is in some header file template <typename T> struct example { T value; }; // valid typedefs typedef std::string type_string; typedef example<type_string> string_example; // Explicit instantiation declaration // QUESTION 2: Is this valid code? if not why not? extern template string_example; // -> at least this compiles, but is it OK? 

As indicated in the above comment, is it correct to use typedef in the extern template declaration , as in the above example, and why this compiler is different from Case1 where it is missing.

I read about similar cases, but none of them gives a detailed answer to the above 2 questions. Detailed development is greatly appreciated!

+5
source share
1 answer
 template class int_example; 

not legal. C ++ 11 Stanard:

14.7.2 Explicit Copying

2 Syntax for explicit instantiation:

explicit specification:
extern opt template Announcement

There are two forms of explicit instantiation: an explicit instance definition and an explicit declaration of creation. An explicit declaration of creation begins with the keyword extern .

3 If the explicit instantiation refers to a class or a member class, the specified type specifier in the declaration must contain the identifier simple-template-id.

simple-template-id is defined in Templates A.12 as:

simple ID template:
template-name < template-argument-list opt >

int_example does not qualify as a simple identifier template.
example<int> can be considered the identifier simple-template-id.

However, by this logic

 extern template string_example; 

also not legal. I do not know how this works for you. I got the following error when I tried to compile such a line in g ++ 4.9.3.

 socc.cc:15:31: error: expected unqualified-id before ';' token extern template string_example; // -> compile time error 
+2
source

Source: https://habr.com/ru/post/1239408/


All Articles