简体   繁体   中英

Class - namespace and template member function specialisation

I have this code:

In Ah

namespace MyUtils 
{
    class A 
    {
       public:
          A();
          ~A();

         template <typename T> Set(T val);
         template <typename T> Set(T * val);

    }

    template <typename T>
    void A::Set(T * val)
    {

    }
}

In A.cpp, I have this

using namespace MyUtils;

template <>
void A::Set<int>(int val)
{
}

template <>
void A::Set<char *>(char * val)
{

}

This kind of logic compiles OK In MSVC or in Xcode. But on Linux, using gcc (g++), I got

error: specialization of 'template void MyUtils::A::Set(T)' in different namespace

Bug in MSVC and Xcode.

From 14.7.2 Explicit instantiation:

An explicit instantiation shall appear in an enclosing namespace of its template.

I also consider this as a bug because according to the C++ Standard ( section 14.7.3 Explicit specialization )

2 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).

So you should use the fully qualified name

template <>
void MyUtils::A::Set<int>(int val)
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM