是否可以在 .cpp 文件的模板类(结构)中编写非模板方法的实现?我读过模板方法应该写在.h上,但我的方法不是模板方法,虽然它属于模板类。这是我的.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 */
我试图serialize()
在 .cpp 文件中编写方法的实现,如下所示:
#include "key_value.h"
using namespace types;
template <class T, class U>
string key_value<T, U>::serialize()
{
// Code here returning string
}
以错误结束:Redefinition of 'serialize'
这样做的正确方法是什么?