C++ Template:部分模板 模板类中的功能特化
我想专门研究模板类中的特定功能。
例如:
template<class T>
class A
{
public :
void fun1(T val);
void fun2(T val1, T val2);
};
template <class T>
void A<T>::fun1(T val)
{
// some task 1;
}
template <class T>
void A<T>::fun2(T val1, T val2)
{
// some task 2;
}
template <>
void A<char*>::fun2(char* val1, char* val2)
{
// some task 2 specific to char*;
}
当我做这样的事情时,我收到错误说 fun2() 的多个定义 请告诉我为什么这是错误的以及实现这一点的正确方法。
I want to specialize specific function in template class.
Eg:
template<class T>
class A
{
public :
void fun1(T val);
void fun2(T val1, T val2);
};
template <class T>
void A<T>::fun1(T val)
{
// some task 1;
}
template <class T>
void A<T>::fun2(T val1, T val2)
{
// some task 2;
}
template <>
void A<char*>::fun2(char* val1, char* val2)
{
// some task 2 specific to char*;
}
when I do something like this, I get error saying multiple definition for fun2()
Please let me why this wrong and also the correct way to implement this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议采用以下方法。定义一个名为
implementation
的私有
函数模板来处理一般情况,并重载(不专门化< /em>)实现
来处理T=char*
时的特定情况。然后从fun2()
调用implementation
并传递第三个参数,如下所示。将根据模板参数T
选择正确的实现
:类型为
selector
(或selector<;)的第三个参数。 char*>
) 有助于选择正确的实现。I would suggest the following approach. Define a
private
function template calledimplementation
to handle the general case, and overload (not specialize)implementation
to handle the specific case whenT=char*
. Then fromfun2()
, callimplementation
passing a third argument as shown below. The correctimplementation
will be selected based on the template argumentT
:The third argument of type
selector<T>
(orselector<char*>
) helps selecting the correct implementation.您的方法
fun2()
本身不是template
方法,尽管它是template
类的成员。我没有找到合适的技术术语,但简单来说,专门化fun2()
将创建正常函数定义的效果。将定义放在头文件中会出现多个定义错误。要解决这个问题,只需添加一个
内联
关键字,链接器错误就会消失!编辑:这可以解决链接器错误。但您仍然无法使用
A::fun2
。最终,它归结为这样一个事实:您需要专门化整个类 A
或重载fun2
A
内的 (char*, char*)Your method
fun2()
is not atemplate
method as itself, though it's a member of atemplate
class. I don't find the proper technical term but in simple words, specializingfun2()
will create an effect of a normal function definition. Putting the definition in header file will give you multiple definition error.To solve this problem, just put an
inline
keyword and the linker error will go away!Edit: This solves the linker error. But still you cannot use the
A<char*>::fun2
. Ultimately it boils down to the very fact that you need to specialize the wholeclass A<char*>
or overload thefun2(char*, char*)
withinA<T>
相应地分割你的代码,它应该可以工作,例如:
Ah
A.cpp
Amain.cpp
编译和链接,它应该做正确的事情......
Split your code accordingly and it should work, for example:
A.h
A.cpp
Amain.cpp
Compile and link, and it should do the right thing...