模板类中的C ++非模板方法 [英] C++ Non Template Method in Template Class
问题描述
是否可以在.cpp文件的模板类(struct)中编写非模板方法的实现?我已经阅读,模板方法应该写在.h,但我的方法不是模板方法,虽然它属于模板类。这是我的.h中的代码:
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 */
我尝试在.cpp文件中写入方法 serialize()
的实现,如下所示:
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
}
结束时出现错误:重新定义'serialize'
如何正确地执行此操作?
How is the proper way to doing this?
推荐答案
这不可能 * 。想想为什么模板首先需要在头文件中:所以每个使用从模板实例化的代码的.cpp文件可以访问它(模板仅根据需求实例化)。
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.
* 一如既往,如果显式实例化是一个选项,你可以定义一个类模板的成员函数。成员函数,并在.cpp文件中提供所有必需的实例化实例。
* 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.
这篇关于模板类中的C ++非模板方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!