如何使自定义类型能够与boost::format的%运算符一起使用?

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;

我一直在学习美化 C++ STL 容器,这与我的问题有些关联,但这让我花了几天时间去复习和学习涉及auto和其他语言特性的问题。我还没有完成所有的调查。

有人能回答这个具体的问题吗?

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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接