2

I'm struggling with templates. The following compiles for me just fine:

//foo.h
class foo {
public:
    template <typename T>
    void swap(T* values, uint8_t offset)
    {
        T swp = values[offset];
        values[offset] = values[offset + 1];
        values[offset + 1] = swp;
    }
};

This does not:

//foo.h
class foo {
public:
    template <typename T>
    void swap(T* values, uint8_t offset);
};

//foo.cpp
template <typename T>
void foo::swap<T>(T* values, uint8_t offset)
{
    T swp = values[offset];
    values[offset] = values[offset + 1];
    values[offset + 1] = swp;
}

I get the error message

error: function template partial specialization 'swap<T>' is not allowed

I don't know what that means so I'm unclear on how to proceed. Thanx in advance.

user1325543
  • 523
  • 3
  • 12

1 Answers1

2

Remove the <T>:

template <typename T>
void foo::swap(T* values, uint8_t offset)
{
    // …
}

That syntax is for template specialization.

Also, you will most likely want your template definitions in the header file, see Why can templates only be implemented in the header file?.

Community
  • 1
  • 1
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
  • Maybe worth to mention that templates shall be defined in the header http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file?rq=1 – Christophe May 07 '16 at 22:37
  • 1
    @Christophe Added. – Emil Laine May 07 '16 at 22:39
  • That did the trick. Apparently of all the things I tried, that wasn't one of them. I'm still working my noodle around the concept, but this is a start at least. Thanx. – user1325543 May 09 '16 at 16:21