template External Linkage ?can anyone Explain this?

后端 未结 4 1269
夕颜
夕颜 2021-02-10 02:05

A template name has linkage (3.5). A non-member function template can have internal linkage; any other template name shall have external linkage. Entities generat

4条回答
  •  再見小時候
    2021-02-10 02:33

    Just by reading carefully the quote you wrote you will notice that, except non-member function templates that might have internal linkage, all other templates have external linkage. There is no need to add keywords, nor keywords can be added there.

    The description of what linkage means is in §3.5/2, in particular external linkage is defined as:

    When a name has external linkage, the entity it denotes can be referred to by names from scopes of other translation units or from other scopes of the same translation unit.

    To force internal linkage of a template non-member function you can use the static keyword, but you cannot do the same with other templates:

    template 
    static void foo( T ) {}
    

    Note that you can achieve a somehow similar effect as internal linkage by using anonymous namespaces.

    Internal linkage: §3.5/2

    When a name has internal linkage, the entity it denotes can be referred to by names from other scopes in the same translation unit.

    Note that the difference is that it cannot be referred from other translation units.

    namespace {
       template 
       class test {};
    }
    

    While the unnamed namespace does not make the linkage internal, it ensures that there will be no name collision as it will be in a unique namespace. This uniqueness guarantees that the code is not accessible from other translation units. Unnamed namespaces are considered to be a better alternative to the static keyword §7.3.1.1/2

    The use of the static keyword is deprecated when declaring objects in a namespace scope (see annex D); the unnamed-namespace provides a superior alternative

    On the other hand, when you say that you:

    know about external linkage using the keyword extern "C"

    You don't. extern "C" is not a request for external linkage. Reread the spec. extern "C" is a linkage-specification and instructs the compiler to use "C" style linkage within the block to interact with C code or libraries that already work that way, like dlopen and family. This is described in §7.5

提交回复
热议问题