是否可以在 .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'
这样做的正确方法是怎样的?
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).
因此,在某种程度上,您可以将类模板视为数据布局(数据成员)的模板加上一组模板,每个模板对应一个成员函数。因此,模板类的所有成员都被视为模板。您甚至可以显式地专门化类模板的成员函数。
* 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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)