C++ Non Template Method in Template Class

2020-08-12 03:36发布

问题:

Is it posible to write implementation of non template method in template class(struct) at .cpp file? I have read that template method should be written on .h, but my method is not template method although it belongs to template class. Here is the code in my .h:

#include <iostream>

#ifndef KEY_VALUE_H
#define KEY_VALUE_H

using namespace std;

namespace types
{
    template <class T, class U>
    struct key_value
    {
        T key;
        U value;

        static key_value<T, U> make(T key, U value)
        {
            key_value<T, U> kv;

            kv.key = key;
            kv.value = value;

            return kv;
        };

        string serialize()
        {
            // Code to serialize here I want to write in .cpp but fails.
        }
    };
}


#endif /* KEY_VALUE_H */

I tried to write the implementation of method serialize() in .cpp file like this:

#include "key_value.h"

using namespace types;

template <class T, class U>
string key_value<T, U>::serialize()
{
    // Code here returning string
}

Ended up with error: Redefinition of 'serialize'

How is the proper way to doing this?

回答1:

It's not possible*. Think about why templates need to be in header files in the first place: so that every .cpp file which uses code instantiated from a template can access it (templates are instantiated on demand only).

So in a way, you can think of a class template as a template for data layout (data members) plus a set of templates, one for each member function. Therefore, all members of a template class are treated as templates. You can even explicitly specialise a member function of a class template.

* As always, if explicit instantiation is an option, you can define the member function in a .cpp file and provide all required expicit instantiations in that .cpp file.