8

我想知道必须在类中实现哪些函数和/或运算符才能与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和各种其他语言特性的日子。我还没有完成所有这些调查。

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

4

1 回答 1

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;
}
于 2012-11-10T22:23:53.310 回答