使用boost :: format的%运算符的自定义类型有哪些要求?

Dan*_*aum 8 c++ templates boost

我想知道必须在类中实现哪些函数和/或运算符才能与boost::format %运算符一起使用.

例如:

class A
{
    int n;
    // <-- What additional operator/s and/or function/s must be provided?
}

A a;
boost::format f("%1%");
f % a;
Run Code Online (Sandbox Code Playgroud)

我一直在研究Pretty-print C++ STL容器,它在某些方面与我的问题有关,但这让我进入了几天相关的审查和学习涉及的问题auto和各种其他语言功能.我还没有完成所有这些调查.

有人可以回答这个具体问题吗?

mfo*_*ini 4

您只需要定义一个适当的输出运算符(operator<<):

#include <boost/format.hpp>
#include <iostream>

struct A
{
    int n;
    
    A() : n() {}
    
    friend std::ostream &operator<<(std::ostream &oss, const A &a) {
        oss << "[A]: " << a.n;
        return oss;
    }
};

int main() {
    A a;
    boost::format f("%1%");
    std::cout << f % a << std::endl;
}
Run Code Online (Sandbox Code Playgroud)