Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the requirements for a custom type to work with boost::format's % operator?

I would like to know what function/s and/or operators must be implemented within a class to work with the boost::format % operator.

For example:

class A
{
    int n;
    // <-- What additional operator/s and/or function/s must be provided?
}

A a;
boost::format f("%1%");
f % a;

I have been studying Pretty-print C++ STL containers, which is related in some ways to my question, but this has sent me into days of related review and learning regarding issues involving auto and various other language features. I'm not yet done with all of this investigation.

Can someone answer this specific question?

like image 444
Dan Nissenbaum Avatar asked Nov 10 '12 22:11

Dan Nissenbaum


1 Answers

You just need to define a proper output operator(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;
}
like image 118
mfontanini Avatar answered Sep 20 '22 15:09

mfontanini