0

我重载do_in了以下方法std::codecvt

#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方法?

4

1 回答 1

2

我认为应该解决的第一件事std::codecvt是仅使用系列方面,std::basic_filebuf因为仅在处理外部设备时才需要代码转换。在您的代码中,您将语言环境注入到std::cin中,它有一个进行代码转换的缓冲区。

当然,仍然可以在程序中执行代码转换,但是阻止代码工作的方面是它继承自std::codecvt<>无法进行转换的专业化。的char => char特化std::codecvt<>没有定义转换,因此do_in()不会被调用,因为没有必要在两种类型之间进行转换。

我尝试运行您的代码,但将继承的方面更改为std::codecvt<wchar_t, char, std::mbstate>并使用宽字符文件流并且它有效

如果您希望这也适用于窄字符流,我建议创建一个流缓冲区,通过underflow().

于 2014-03-27T17:04:22.300 回答