Specialized Namespace Function

I want to specialize a function template. This function is declared in the namespace:

namespace foo { template <int> void function(); } 

(For simplicity, the template is int , whereas in my production code it is an enum class , but this is the same problem. The same goes for the type based template)

Now I want to specialize it for a specific value:

 template <> void foo::function<0>() { } 

This does not compile with g++ -std=c++11 (versions 4.6, 4.7, 4.8 and 4.9):

specialization "template void foo :: function () in different namespaces [-fpermissive]

clang++ -std=c++11 accepts this code.

g ++ also accepts the following snippet:

 namespace foo { template <> void function<0>() { } } 

Who is right, gcc or clang?

+5
source share
1 answer

According to the standard, ยง14.7.3 / 2, my emphasis is:

Explicit specialization is declared in the namespace spanning the specialized pattern. Explicit specialization, the declarator identifier is not qualified , must be declared in the nearest spanning namespace template, or, if the namespace is built-in (7.3.1), any namespace from its spanning namespace is established.

You should put template<> function<0>(); in namespace foo . However, this rule only applies to an unqualified ad ID. When you provide an identifier with qualifications (as in foo::function<0> ), I believe the sentence should not apply, which makes clang right here.

For example, if you ask the function question, I expect the following:

 namespace foo { template <> void function<0>(); // valid: unqualified explicit specialization // in the nearest enclosing namespace of the // template } namespace bar { template <> void function<1>(); // invalid: unqualified explicit specialization // in the wrong namespace } struct baz { template <> void function<2>(); // invalid: unqualified explicit specialization // not in namespace scope }; template <> void foo::function<3>(); // valid: qualified explicit specialization // is in a namespace, and id is qualified template <> void bar::function<4>(); // invalid: there is no bar::function // to specialize 
+8
source

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


All Articles