Click here to Skip to main content
15,896,912 members
Articles / Programming Languages / VC++

Static Value Lists

Rate me:
Please Sign up or sign in to vote.
4.60/5 (7 votes)
25 Aug 2011CPOL18 min read 23.6K   246   17  
An introduction to advanced template metaprogramming using an explanatory project
#pragma once

namespace lobster {

namespace stream_fo {

template<typename char_type> 
inline std::basic_string<char_type> to_1line_string(const char_type* text, size_t max_width) {
    std::basic_ostringstream<char_type> oss; oss << text;
    std::basic_string<char_type> str = oss.str();
    
    if (str.size() > max_width) {
        size_t n_ellipsis = std::min(max_width, (size_t) 4);
        str = str.substr(0, max_width - n_ellipsis);
        if (n_ellipsis > 0) str += char_type(' ');
        for (size_t i = 1; i <= n_ellipsis; i++) str += char_type('.');
    }
    return str;
}

template<typename char_type>
inline void write_line(
    std::basic_ostream<char_type>& s, 
    char_type line_char = (char_type) ('-'),
    size_t width = 79
) { 
    s << std::setfill(line_char) << std::setw(width) << "" << std::endl;
}    

template<typename char_type>
inline void write_headline(
    std::basic_ostream<char_type>& s, 
    const char_type* text,
    char_type underline_char = (char_type) ('-'),
    size_t max_width = 79
) {
    std::basic_string<char_type> str = to_1line_string(text, max_width);
    
    s << str << std::endl;
    write_line(std::cout, underline_char, str.size());
}


template<typename char_type>
inline void write_box(
    std::basic_ostream<char_type>& s, 
    const char_type* text,
    char_type box_char = (char_type) ('*'),
    size_t box_width = 79
) {
    const size_t w = box_width - 2;
    
    std::basic_string<char_type> str = to_1line_string(text, w);
    if (str.size() > w) str = str.substr(0, w);
    
    const size_t w_pre = (w - str.size()) / 2;
    const size_t w_post = w - str.size() - w_pre;
   
    write_line(std::cout, '*', box_width);

    s << box_char
      << std::setfill((char_type) (' ')) 
      << std::setw(w_pre) 
      << "" 
      << str
      << std::setw(w_post) 
      << "" 
      << box_char
      << std::endl;

    write_line(std::cout, '*', box_width);
}

}

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions