[英]std::codecvt::do_in method overloading vs the rest of base methods
我重载了std::codecvt
do_in
方法:
#include <iostream>
#include <locale>
#include <string>
class codecvt_to_upper : public std::codecvt<char, char, std::mbstate_t> {
public:
explicit codecvt_to_upper(size_t r = 0) : std::codecvt<char, char,
std::mbstate_t>(r) {}
protected:
result do_in(state_type& state, const extern_type* from,
const extern_type* from_end, const extern_type*& from_next,
intern_type* to, intern_type* to_end, intern_type*& to_next)
const;
result
do_out(state_type& __state, const intern_type* __from,
const intern_type* __from_end, const intern_type*& __from_next,
extern_type* __to, extern_type* __to_end,
extern_type*& __to_next) const {
return codecvt_to_upper::ok;
}
result
do_unshift(state_type& __state, extern_type* __to,
extern_type* __to_end, extern_type*& __to_next) const {
return codecvt_to_upper::ok;
}
int
do_encoding() const throw () {
return 1;
}
bool
do_always_noconv() const throw () {
return false;
}
int
do_length(state_type&, const extern_type* __from,
const extern_type* __end, size_t __max) const {
return 1;
}
int
do_max_length() const throw () {
return 10;
}
};
codecvt_to_upper::result codecvt_to_upper::do_in(state_type& state,
const extern_type* from, const extern_type* from_end, const
extern_type*& from_next, intern_type* to, intern_type*
to_end, intern_type*& to_next) const {
codecvt_to_upper::result res = codecvt_to_upper::error;
const std::ctype<char>& ct = std::use_facet<std::ctype<char> >(
std::locale());
const extern_type* p = from;
while( p != from_end && to != to_end) {
*to++ = ct.toupper( *p++);
}
from_next = p;
to_next = to;
res = codecvt_to_upper::ok;
return res;
}
并以这种方式使用:
int main(int argc, char** argv) {
std::locale ulocale( std::locale(), new codecvt_to_upper);
std::cin.imbue( ulocale);
char ch;
while ( std::cin >> ch) {
std::cout << ch;
}
return 0;
}
但是没有调用do_in
重载。 我是否正确地重载了它? std::codecvt<char, char, std::mbstate_t>
(以及如何)的 do_in
方法我必须更改才能使我的方面调用do_in
方法?
我认为应该解决的第一件事是std::codecvt
系列facet仅由std::basic_filebuf
使用,因为只有在处理外部设备时才需要代码转换。 在您的代码中,您将语言环境填充到std::cin
,它具有不执行代码转换的缓冲区。
当然,仍然可以在程序中执行代码转换,但是关于阻止代码工作的方面的事情是它继承了std::codecvt<>
,它无法进行转换。 std::codecvt<>
的char => char
std::codecvt<>
没有定义转换,因此不会调用do_in()
因为不需要在两种类型之间进行转换。
我尝试运行你的代码,但是将继承的facet更改为std::codecvt<wchar_t, char, std::mbstate>
并使用了宽字符文件流并且它工作正常 。
如果你想让它适用于窄字符流,我建议创建一个流缓冲区,通过underflow()
转发大写字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.