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
  • 503
  • 3
  • 12
  • 1
    See http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file?rq=1 for more information on template definitions in .cpp files. – Jonathan Potter May 07 '16 at 22:35
  • @rwols Sure you can, see the link in the above comment. – emlai May 07 '16 at 22:36

1 Answers1

1

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
emlai
  • 39,703
  • 9
  • 98
  • 145
  • 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. – emlai 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