【问题标题】:What are the requirements for a custom type to work with boost::format's % operator?自定义类型与 boost::format 的 % 运算符一起使用有什么要求?
【发布时间】:2012-10-30 20:42:52
【问题描述】:

我想知道必须在类中实现哪些函数和/或运算符才能与 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 和其他各种语言功能的问题上进行了数天的相关审查和学习。我还没有完成所有这些调查。

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

【问题讨论】:

    标签: c++ templates boost


    【解决方案1】:

    你只需要定义一个合适的输出操作符(operator&lt;&lt;):

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

    【讨论】:

      猜你喜欢
      • 2020-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-15
      • 2014-08-06
      • 2017-11-23
      • 2013-11-29
      • 1970-01-01
      相关资源
      最近更新 更多