c++templatesnamespacestemplate-specializationexplicit-specialization

How to explicitly specialize a function template from within another namespace?


For readability reasons, I would like to specialize a function template close to the definition of a class which is declared inside a namespace:

#include <iostream>

template<typename T> void my_function() {
    std::cout << "my_function default" << std::endl;
}

namespace Nested {
    class A {};
    template<> void my_function<A>() {
        std::cout << "my_function specialization for A" << std::endl;
    }
}

However, with the above code I get the following error from clang++ 4.0:

 error: no function template matches function template specialization 'my_function'

This seems to be a namespacing problem. How can I get the above to work (without moving the template function specialization out of the Nested namespace)?

Edit: I have also tried adding ::my_function in the specialization:

test.cpp: error: definition or redeclaration of 'my_function' cannot name the global scope
        template<> void ::my_function<A>() {
                        ~~^

Solution

  • That is not possible, specialization must reside in the same namespace as template itself:

    14.7.3 Explicit specialization [temp.expl.spec]

    2 An explicit specialization shall be declared in a namespace enclosing the specialized template. An explicit specialization whose declarator-id or class-head-name 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).

    so you have to rewrite your code like this:

    namespace Nested {
    class A {};
    } // namespace Nested
    
    template<> void my_function<Nested::A>() {
        std::cout << "my_function specialization for A" << std::endl;
    }