【cxx-prettyprint源码学习】自定义支持及其它

2016-12-22  本文已影响0人  长不胖的Garfield

如何支持数组输出

经过对is_container及print_container_helper的分析,可以得知,如果要支持数组输出,需要提供const_iterator、begin、end:

template<typename T>
struct array_wrapper_n
{
     typedef const T * const_iterator;
     typedef T value_type;

     array_wrapper_n(const T * const a, size_t n) : _array(a), _n(n) { }
     inline const_iterator begin() const { return _array; }
     inline const_iterator end() const { return _array + _n; }

private:
    const T * const _array;
    size_t _n;
};

包裹并提供全局快捷访问函数

template<typename T>
inline pretty_print::array_wrapper_n<T> pretty_print_array(const T * const a, size_t n)
{
    return pretty_print::array_wrapper_n<T>(a, n);
}

使用方式如下:

std::cout << pretty_print_array(arr, n) << std::endl

支持自定义分隔符

支持自定义分隔符的关键是将print_container_helperTDeimiters类型替换成为自定义的分隔符类型:

提供支持Custom Deimiters的输出类:

    struct custom_delims_base
    {
        virtual ~custom_delims_base() { }
        virtual std::ostream & stream(::std::ostream &) = 0;
        virtual std::wostream & stream(::std::wostream &) = 0;
    };

    template <typename T, typename Delims>
    struct custom_delims_wrapper : custom_delims_base
    {
        custom_delims_wrapper(const T & t_) : t(t_) { }

        std::ostream & stream(std::ostream & s)
        {
            return s << print_container_helper<T, char, std::char_traits<char>, Delims>(t);
        }

        std::wostream & stream(std::wostream & s)
        {
            return s << print_container_helper<T, wchar_t, std::char_traits<wchar_t>, Delims>(t);
        }

    private:
        const T & t;
    };

定义全局的Custom Deimiters:

    template <typename Delims>
    struct custom_delims
    {
        template <typename Container>
        custom_delims(const Container & c) : base(new custom_delims_wrapper<Container, Delims>(c)) { }

        std::unique_ptr<custom_delims_base> base;
    };

提供ostream <<输出方法:

    template <typename TChar, typename TCharTraits, typename Delims>
    inline std::basic_ostream<TChar, TCharTraits> & operator<<(std::basic_ostream<TChar, TCharTraits> & s, const custom_delims<Delims> & p)
    {
        return p.base->stream(s);
    }
上一篇 下一篇

猜你喜欢

热点阅读