问题描述
限时送ChatGPT账号..已经提出了许多问题,它们与我将在这里提出的问题相似,但我认为它们并不相同.
Many questions have been asked and they are similar to the one I am going to ask here, but they are not the same I think.
我有一个模板类:
namespace app {
template <typename T>
class MyCLass {
public:
void dosome();
void doother();
}
} /*ns*/
和实现:
template <typename T>
app::MyClass<T>::dosome() {}
template <typename T>
app::MyClass<T>::doother() {}
当我有一个该类的实例时,将 char
作为模板参数提供给它,我希望函数 dosome()
以完全不同的方式运行.但我只是希望该函数的行为有所不同,其他一切都必须保持不变.
When I have an instance of that class to which a char
is provided as template parameter, I want function dosome()
to behave in a totally different way.
But I just want that function to behave differently, everything else must still act the same.
我尝试输入:
template<>
app::MyCLass<char>::dosome() {
}
但是编译器告诉我我正在尝试在不同的命名空间中创建一个专业化.
But the compiler tells me that I am trying to create a specialization in a different namespace.
所以当我有这样的代码时:
So when I have a code like this:
app::MyCLass<int> a;
app::MyCLass<char> b;
a.dosome(); // This must call the generic template definition
b.dosome(); // This must call the specialization
a.doother(); // This must call the generic template definition
b.doother(); // This must call the generic template definition
在其他问题中,我看到人们为整个班级创造了完全不同的专业.但我只想要一种方法的特化.
In other questions I saw people creating totally different specialization of the entire class. But I only want a specialization of a single method.
推荐答案
你可以为所欲为:http://ideone/oKTFPC
//标题
namespace My
{
template <typename T>
class MyClass {
public:
void dosome();
void doother();
};
template <typename T> void MyClass<T>::dosome() {}
template <typename T> void MyClass<T>::doother() {}
template<> void MyClass<char>::dosome();
}
//cpp 或在标题中
// cpp or in header
template<>
void My::MyClass<char>::dosome() {
std::cout << "specialization" << std::endl;
}
或使用替代符号
namespace My {
template<>
void MyClass<char>::dosome() {
std::cout << "specialization" << std::endl;
}
}
这篇关于如何在 C++ 中的模板化类中为单个方法创建特化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论