2012-11-10 22 views
7

我想知道在一個類中必須實現哪些功能和/或操作符來與boost::format%操作符一起工作。自定義類型與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問題,以及其他各種語言相關的審查和學習的日子特徵。我還沒有完成這項調查。

有人可以回答這個問題嗎?

回答

3

你只需要定義一個適當的輸出操作(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; 
} 
相關問題