This piece below is supposed to be primarily for a string view with T={char, const char}
being the primary intended template instantiation target.
The cmp function is supposed to compare the views analogously to strcmp
. The problem is that while char*
happily converts to const char*
I don't know how to get SVec<char>
to convert to SVec<const char>
just as happily.
The last line (cout<<(cmp(rv, rvc));
) won't compile. I have to do the convertion explicitly (cmp(SVec<const char>(rv), rvc)
). Can it be automatic like with char*
to const char*
?
The code (much simplified):
template <typename T>
class SVec {
protected:
T* begin_;
size_t size_;
public:
SVec(T* begin, size_t size) : begin_(begin), size_(size) {};
SVec(T* begin, T* end) : begin_(begin), size_(end-begin) {};
SVec(T* begin) : begin_(begin) { while (*(begin++)) {}; size_ = begin - 1 - begin_; }
//^null element indicates the end
///Conversion
operator SVec<const T>() const { return SVec<const T>(begin_, size_); }
};
//General lexicographic compare
template <typename T>
inline int cmp(const SVec<const T>& l, const SVec<const T> & r){
return 1;
}
//Char specialization
template <> inline int cmp<char>(const SVec<const char>& l, const SVec<const char>& r){
return 1;
}
//Explicit instantiation
template int cmp<char>(const SVec<const char>& l, const SVec<const char>& r);
#include <iostream>
int main(){
using namespace std;
char ar[] = "st";
SVec<char> sv = ar;
SVec<const char> svc = "str";
cout<<(cmp(SVec<const char>(sv), svc));
cout<<(cmp(sv, svc));
}
(The name was supposed to mean Read-only vector but it's supposed to be a nonrezi
Aucun commentaire:
Enregistrer un commentaire