我有一个称为Vector的模板类,我想根据类所采用的类型来专门化其方法之一my_compare。我能够成功地对大多数类型进行专门化,但是如果我使用a指针类型。
在cpp文件顶部:
template <typename T> class Vector {
public:
...
bool my_compare(const T a, const T b);
...
};
稍后的:
template <typename T> bool Vector<T>::my_compare(const T a, const T b){
return (a < b);
}
template <> bool Vector<Mystring>::my_compare(const Mystring a, const Mystring b){
//cout << "did a mycompare for stringies";
return (strcmp(a.c_str(), b.c_str()) > 0);
}
template <> bool Vector<char*>::my_compare(const char* a, const char* b){
return (strcmp(a, b) > 0);
}
该专业化适用于Mystring,但不适用于char *。我收到以下错误:
iterator.cpp:106:18: error: template-id ‘my_compare<>’ for ‘bool Vector<char*>::my_compare(const char*, const char*)’ does not match any template declaration
template <> bool Vector<char*>::my_compare(const char* a, const char* b){
^~~~~~~~~~~~~
当我使用不同的指针类型(例如int *或Mystring *)时,编译器会抛出相同的错误。我正在使用G ++作为编译器。任何人都知道我在做错什么以及如何解决?谢谢您的帮助!
这有些微妙,但这是因为const char*
与并不相同char* const
。
您的函数my_compare(const T a, const T b)
需要一个const T
。T
在这种情况下是char*
。因此,您需要一个常量指针而不是指向常量的指针。
添加预选赛的规则让你把const
和volatile
向左的类型,尽管大多数改性剂应用于从右到左。换句话说,您正在定义:
my_compare(char const* a, char const* b)
代替:
my_compare(char* const a, char* const b)
其他一些参考资料:
https://zh.wikipedia.org/wiki/Const_(计算机编程)
从左侧读取时,从右向左读取元素很重要。因此,an
int const *
成为指向const int的指针,而不是指向int的const指针。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句