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

时间:2012-11-10 22:09:57

标签: 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;

我一直在研究Pretty-print C++ STL containers,这在某种程度上与我的问题有关,但这让我在涉及auto和其他各种语言功能的问题上进行了相关的审查和学习。我还没有完成所有这些调查。

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

1 个答案:

答案 0 :(得分: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;
    }
};

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