Boost logo

Boost Users :

Subject: Re: [Boost-users] [units] - overriding output
From: Matthias Schabel (boost_at_[hidden])
Date: 2009-09-15 16:09:23


> What is the correct way to override the << op for a unit so that it
> say prints "Pa" instead of "m^-1 kg s^-2"?
>
> I tried this and no worky:
>
> #include <boost/units/io.hpp>
>
> namespace boost { namespace units {
>
>
> template<>
> inline std::string
> name_string< boost::units::pressure_dimension,
> boost::units::si::system >(const boost::units::si::pressure&)
> {
> return "Pa";
> }
>
> }} // boost::units

"name_string" and "symbol_string" aren't templated - they are
overloaded functions, so the template is not correct. Also, you
defined "name_string", which is for fully-formatted unit output (e.g.
"pascal" vs. "Pa"), so you are overloading the wrong function here.
The easy way is to include the SI IO header :

#include <boost/units/io.hpp>
#include <boost/units/quantity.hpp>
#include <boost/units/systems/si.hpp>
#include <boost/units/systems/si/io.hpp>

#include <iostream>

using namespace boost::units;

int main(void)
{
        std::cout << name_format << 1.0*si::pascal << std::endl
                  << symbol_format << 1.0*si::pascal << std::endl;
}

giving

1 pascal
1 Pa

The default output formatter is symbol format. Your code, with fixes
of the bugs above, works as well :

#include <boost/units/io.hpp>
#include <boost/units/systems/si.hpp>

namespace boost {
        namespace units {
        
        inline std::string symbol_string(const si::pressure&)
        {
                return "Pa";
        }
}
} // boost::units

#include <iostream>

using namespace boost::units;

int main(void)
{
        std::cout << 1.0*si::pascal << std::endl;
}

HTH,

Matthias



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net