类的自定义操纵器

Custom manipulator for class

本文关键字:操纵 自定义      更新时间:2023-10-16

我正在尝试编写一个带有参数的流操纵器。我上课的日期是3点(年、月、日)。所以我需要制作机械手date_format(const char*)。例如:

CDate a(2006, 5, 15);
cout <<"DATE IS : " << date_format("%Y-hello-%d-world-%m-something-%d%d") << a;

输出为:

DATE IS : 2006-hello-15-world-5-something-1515

我想我需要使用

ios_base & dummy_date_format_manipulator ( ios_base & x )
{
    return x;
}
ios_base & ( * ( date_format ( const char * fmt ) ) )( ios_base & x )
{
    return dummy_date_format_manipulator;
}

但我不知道怎么做。

您可以使用pword数组。C++中的每个iostream都有两个与其关联的数组

ios_base::iword - array of ints
ios_base::pword - array of void* pointers

你可以在其中存储你自己的数据。要获得一个索引,它引用了所有iwordpword数组中的一个空元素,你应该使用函数std::ios_base::xalloc()。它返回int,您可以将其用作*word中的唯一索引。您应该在启动时获得一次该索引,然后将其用于*word的所有操作。

然后编程你自己的操纵器将看起来像:

操纵器函数接收对ios_base对象的引用和指向格式字符串的指针,只需将该指针存储在pword

iosObject.pword(index_from_xalloc) = formatString

然后重载运算符<<>>)以相同的方式从iostream对象获得格式字符串。之后,您只需参照格式进行转换。

带参数的操纵器与不带参数的操作器工作方式不同!只是具有适当输出运算符的类,该运算符不是输出值而是操纵流的状态。为了操作流状态,您可能会设置一个suitabe值,该值存储在与数据流相关的iword()pword()中,并由输出运算符使用。

正如chris所建议的,我认为您应该只使用tm,而不是您的自定义日期类:

tm a{0, 0, 0, 15, 5, 2006 - 1900};
cout << put_time(&a, "%Y-hello-%d-world-%m-something-%d%d");

如果您必须实现get_timeput_time无法实现的自定义功能,那么您可能希望使用tm成员作为类的一部分,这样您就可以扩展现有的功能:

class CDate{
    tm m_date;
public:
    CDate(int year, int month, int day): m_date{0, 0, 0, day, month, year - 1900}{}
    const tm& getDate() const{return m_date;}
};
ostream& operator<<(ostream& lhs, const CDate& rhs){
    auto date = rhs.getDate();
    return lhs << put_time(&a, "%Y-hello-%d-world-%m-something-%d%d");
}

然后,您可以按如下方式使用CDate

CDate a(2006, 5, 15);
cout << "DATE IS:" << a;

编辑:

再看一遍你的问题,我认为你对插入运算符的工作方式有一个误解,你不能同时传入对象和格式:https://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx

如果您想指定一种格式,但仍然保留CDate类,我再次建议使用put_time:

cout << put_time(&a.getDate(), "%Y-hello-%d-world-%m-something-%d%d");

如果您再次坚持编写自己的格式接受函数,您将需要创建一个可以内联构建的辅助类,并使用插入运算符支持它:

class put_CDate{
    const CDate* m_pCDate;
    const char* m_szFormat;
public:
    put_CDate(const CDate* pCDate, const char* szFormat) : m_pCDate(pCDate), m_szFormat(szFormat) {}
    const CDate* getPCDate() const { return m_pCDate; }
    const char* getSZFormat() const { return m_szFormat; }
};
ostream& operator<<(ostream& lhs, const put_CDate& rhs){
    return lhs << put_time(&rhs.getPCDate()->getDate(), rhs.getSZFormat());
}

您可以按如下方式使用:

cout << put_CDate(&a, "%Y-hello-%d-world-%m-something-%d%d") << endl;

就像Dietmar说的那样,你可以把params推到iword()中,但我发现这种解决方案既乏味又烦人。。

我更喜欢将lambda函数作为iomanip安装,并使用它们直接调用各种类方法或以其他方式就地构建自定义打印。为此,我为主操纵器创建了一个简单的100行模板安装程序/助手类,它可以添加lambda函数作为任何类的操纵器。。

因此,对于你的CDate,你可以将你的操作定义为

std::ostream& dummy_date_format_manipulator (std::ostream& os)
{
    CustomManip<CDate>::install(os,
                        [](std::ostream& oos, const CDate& a)
                        {
                            os << a.year() 
                                << "-hello-" 
                                << a.day()
                                << "-world-" 
                                << a.month() 
                                << "-something-"
                                << a.day() << a.day();
                        });
    return os;
}

然后直接使用<lt;操作来使用manip安装程序的打印助手:

std::ostream& operator<<(std::ostream& os, const CDate& a)
{
    CustomManip<CDate>::print(os, a);
    return os;
}

你基本上完成了。。

mainp安装程序代码和一个完整的工作示例在我的博客文章中:http://code-slim-jim.blogspot.jp/2015/04/creating-iomanip-for-class-easy-way.html

但为了友善。。以下是你想放在.h中的关键部分,它不需要所有的打印输出来演示它的工作原理:

//g++ -g --std=c++11 custom_class_manip.cpp
#include <iostream>
#include <ios>
#include <sstream>
#include <functional>
template <typename TYPE>
class CustomManip
{
private:
    typedef std::function<void(std::ostream&, const TYPE&)> ManipFunc;
    struct CustomManipHandle
    {
        ManipFunc func_;
    };
    static int handleIndex()
    {
        // the id for this Custommaniputors params
        // in the os_base parameter maps
        static int index = std::ios_base::xalloc();
        return index;
    }
public:
    static void install(std::ostream& os, ManipFunc func)
    {
        CustomManipHandle* handle =
            static_cast<CustomManipHandle*>(os.pword(handleIndex()));
        // check if its installed on this ostream
        if (handle == NULL)
        {
            // install it
            handle = new CustomManipHandle();
            os.pword(handleIndex()) = handle;
            // install the callback so we can destroy it
            os.register_callback (CustomManip<TYPE>::streamEvent,0);
        }
        handle->func_ = func;
    }
    static void uninstall(std::ios_base& os)
    {
        CustomManipHandle* handle =
            static_cast<CustomManipHandle*>(os.pword(handleIndex()));
        //delete the installed Custommanipulator handle
        if (handle != NULL)
        {
            os.pword(handleIndex()) = NULL;
            delete handle;
        }
    }
    static void streamEvent (std::ios::event ev,
                             std::ios_base& os,
                             int id)
    {
        switch (ev)
        {
            case os.erase_event:
                uninstall(os);
                break;
            case os.copyfmt_event:
            case os.imbue_event:
                break;
        }
    }
    static void print(std::ostream& os, const TYPE& data)
    {
        CustomManipHandle* handle
            = static_cast<CustomManipHandle*>(os.pword(handleIndex()));
        if (handle != NULL)
        {
            handle->func_(os, data);
            return;
        }
        data.printDefault(os);
    }
};

当然,如果你真的需要这些参数,那么就使用CustomManip::make_installer(…)函数来完成它,但为此你必须访问博客。。