Iterate Over Struct; Easily Display Struct Fields And Values In a RichEdit Box

后端 未结 9 1874
离开以前
离开以前 2020-12-13 22:10

Is there an easier way to display the struct fields and their corresponding values in RichEdit control?

This is what I am doing now:

<
9条回答
  •  暖寄归人
    2020-12-13 22:28

    I don't use C++ Builder, so some of the details of this are likely to be a bit off, but the general idea should be at least reasonably close:

    class richedit_stream { 
        TRichEditControl &ctrl;
    public:
        richedit_stream(TRichEditControl &trc) : ctrl(trc) {}
    
        template 
        richedit_stream &operator<<(T const &value) {
            std::stringstream buffer;
            buffer << value;
            ctrl.Lines->Append(value.str().c_str());
            return *this;
        }
    };
    

    The basic idea is pretty simple: a front-end for a richedit control, that provides a templated operator<<. The operator puts an item into a stringstream to convert it to a string. It then gets the resulting string and appends it to the the lines in the control. Since it's templated, it can work with all the usual types supported by a stringstream.

    This does have shortcomings -- without more work, you won't be able to use manipulators to control formatting of the data as it's converted to a string. Since it's using a stringstream to convert things to strings, it's probably also a bit slower than your code explicitly encoding the type of each conversion. At the same time, you can use fairly clean, simple, idiomatic code in return for a fairly minimal investment.

提交回复
热议问题