tags:

views:

47

answers:

2

Can anyone help me with this code. I'm trying to specialise a method. At the moment it doesn't work with one specialisation (1) but I'd like to ultimately have lots of specialisations (2, 3, 4, 5 etc)

class X
{
public:

    // declaration
    template< int FLD >
    void set_native( char *ptr, unsigned int length );

    // specialisations

    template<> void set_native< 1 >( char *ptr, unsigned int length )
    {
    }

};

The error messages I'm getting are..

x.cpp:13: error: explicit specialization in non-namespace scope 'class X' x.cpp:13: error: template-id 'set_native<1>' for 'void set_native(char*, unsigned int)' does not match any template declaration x.cpp:13: error: invalid function declaration

+1  A: 

Try the following

class X
{
public:

    // declaration
    template< int FLD >
    void set_native( char *ptr, unsigned int length );
};

// specialisations
template<> void X::set_native< 1 >( char *ptr, unsigned int length )
{
}

If it does not work, try adding a templated class behind set_native

template<int FLD> class SetNative;
class X
{
public:    
    // declaration
    template< int FLD >
    void set_native( char *ptr, unsigned int length )
    { return SetNative()(ptr, length); }
};
template<> class SetNative<1>
{
  void operator()( char *ptr, unsigned int length ){...}
};
Benoît
Approach #2 is not necessary, the first is compliant and (afaik) completely portable.
Georg Fritzsche
+1  A: 

As Benoit proposed, you have to specialize the member function in the surrounding namespace:

struct X {
    template<int N> void f() {}
};

template<> void X::f<1>() {} // explicit specialization at namespace scope

This is because of §14.7.3 (C++03):

An explicit specialization shall be declared in the namespace of which the template is a member, or, for member templates, in the namespace of which the enclosing class or enclosing class template is a member.

VC however doesn't conform to the standard in that regard and thus creates some portability headaches.

Georg Fritzsche