本文介绍了只专门化(一部分)模板类的一个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有一个模板类
template<typename T>
class C {
public:
void method1() { ... }
void method2() { ... }
std::string method3(T &t) {
// ...
std::string s = t.SerializeToString();
// ...
return s;
}
// ...
};
并且我想将它专门用于 T = std::string
但只更改 method3(T&)
(保留所有其他方法),或者甚至更好,仅更改method3 的那部分,对于 T = std::string
将简单地变成 std::string s = t;
,对当前代码的影响最小(方法重复较少)签名,更少的子类化),我该怎么做?
and I want to specialize it for T = std::string
but only changing method3(T&)
(keeping all other methods), or even better, only that part of method3, which for T = std::string
would simply become std::string s = t;
, with minimum impact on current code (less repetition of methods signatures, less subclassing), how would I do it?
我正在 C++11 中开发
I'm developing in C++11
推荐答案
你可以像这样使用特化(不需要特化整个类):
You can use specialization like that (no need to specialize the whole class):
template<>
std::string C<string>::method3(string &t) {
// ...
std::string s = t;
// ...
return s;
}
这篇关于只专门化(一部分)模板类的一个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!