已经问了很多问题,它们与我在这里要问的问题相似,但我认为它们并不相同。
我有一个模板类:
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()
以完全不同的方式行事。
但我只是希望该函数的行为有所不同,其他所有内容仍必须表现相同。
我尝试输入:
template<>
app::MyCLass<char>::dosome() {
}
但编译器告诉我,我正在尝试在不同的命名空间中创建专业化。
所以当我有这样的代码时:
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
在其他问题中,我看到人们为整个班级创建了完全不同的专业化。但我只想要单一方法的专业化。
你可以做你想做的:http://ideone.com/oKTFPC http://ideone.com/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 或 header 中
template<>
void My::MyClass<char>::dosome() {
std::cout << "specialization" << std::endl;
}
或使用替代符号
namespace My {
template<>
void MyClass<char>::dosome() {
std::cout << "specialization" << std::endl;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)