Explicit Specialization Outside Namespace Scope: An Error in Non-Standard G
C template programming involves the explicit specialization of class members for efficient code generation. However, the placement of explicit specializations is crucial, as demonstrated by the following code snippet:
template<typename T> class CConstraint { // ... template <typename TL> void Verify(int position, int constraints[]) { } template <> void Verify<int>(int, int[]) { } };
When compiled with g , this code results in the error:
Explicit specialization in non-namespace scope 'class CConstraint'
To understand this error, we need to examine the C standard, which dictates that explicit specializations must be declared within the namespace of which the template is a member. In the above example, CConstraint is not declared inside any namespace, and thus the explicit specialization of Verify
VC compilers, however, are non-compliant in this case, allowing explicit specializations outside namespace scope. This behavior is non-standard and should not be relied upon.
Solution:
To resolve this issue and ensure compliance with the C standard, explicit specializations must be declared within the same namespace as the template they specialize. Here is a corrected version of the code:
namespace MyNamespace { template<typename T> class CConstraint { // ... template <typename TL> void Verify(int position, int constraints[]) { } template <> void Verify<int>(int, int[]) { } }; }
By encapsulating CConstraint within the MyNamespace namespace, we ensure that its explicit specializations are also declared within that namespace, resolving the compilation error.
Additionally, since C 03 prohibits specializing member functions without explicitly specializing the containing class, we could also consider using a free function approach, as suggested in the provided answer:
namespace detail { template <typename TL> void Verify(int, int[]) {} template <> void Verify<int>(int, int[]) {} } template<typename T> class CConstraint { // ... template <typename TL> void Verify(int position, int constraints[]) { detail::Verify<TL>(position, constraints); } };
The above is the detailed content of Why Does Explicit Specialization of Class Members Fail Outside a Namespace in C ?. For more information, please follow other related articles on the PHP Chinese website!