Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When function template is specialized in a different namespace, GCC and clang disagree

See the following code:

namespace ns {

template <typename T>
void func() {}

}

template <>
void ns::func<int>() {}

int main() {}

While clang 3.6 (C++14) compiles fine, GCC 5.2 (C++14) throws the following error

main.cpp:9:20: error: specialization of 'template<class T> void ns::func()' in different namespace [-fpermissive]
 void ns::func<int>() {}
                    ^
main.cpp:4:6: error:   from definition of 'template<class T> void ns::func()' [-fpermissive]
 void func() {}
      ^

So, what does the standard say about this? Who is correct?

like image 256
Lingxi Avatar asked Oct 10 '15 17:10

Lingxi


1 Answers

What does the Standard (n3797) say?

14.7.3    Explicit Specialization    [temp.expl.spec]

An explicit specialization shall be declared in a namespace enclosing the specialized template. An explicit specialization whose declarator-id is not qualified shall be declared in the nearest enclosing namespace of the template, or, if the namespace is inline (7.3.1), any namespace from its enclosing namespace set. Such a declaration may also be a definition. If the declaration is not a definition, the specialization may be defined later (7.3.1.2).

Verdict: Your specialization is an explicit specialization, and it is qualified, meaning that the snippet is legal. As such, the behavior shown by clang is the correct one.


The relevant bug report for gcc:

  • gcc.gnu.org/bugzilla - Bug 56480 - Explicit specialization in a namespace enclosing the specialized template
like image 64
Filip Roséen - refp Avatar answered Nov 14 '22 23:11

Filip Roséen - refp