11

Is there a way to create a shorthand alias for the following line in C++98?

std::precision(3) << std::fixed

And then use the alias as follows:

std::cout << alias << 3.1415926 << std::endl;
11
  • 5
    What is C++ 99? Commented Oct 3, 2016 at 14:07
  • 15
    @LightnessRacesinOrbit The new upcoming 2099 standard. Commented Oct 3, 2016 at 14:08
  • 3
    Probably just use a #define. Commented Oct 3, 2016 at 14:08
  • 2
    That standard has nothing to do with C++. Commented Oct 3, 2016 at 14:13
  • 2
    @GillBates As if it will be finished before the turn of the century. Commented Oct 3, 2016 at 14:13

1 Answer 1

21

The standard way would probably be to create a custom manipulator:

std::ios_base& alias(std::ios_base& str) {
    str.precision(3);
    return std::fixed(str);
}

Then:

std::cout << alias << 3.16464;

See overload (9) of operator<<:

basic_ostream& operator<<(std::ios_base& (*func)(std::ios_base&))

If you want to specify arguments, you need an intermediate structure:

struct alias_t {
    int n;
};

alias_t setalias(int n) { return {n}; }

template <class CharT, class Traits>
std::basic_ostream<CharT, Traits>& 
operator<<(std::basic_ostream<CharT, Traits>& out, const alias_t& alias) {
    return out << std::fixed << std::setprecision(alias.n);
}

// Or if you do not care about genericity:
std::ostream& operator<<(std::ostream& out, const alias_t& alias) {
    return out << std::fixed << std::setprecision(alias.n);
}

Then:

std::cout << setalias(6) << 3.16464;
Sign up to request clarification or add additional context in comments.

9 Comments

Beautiful. Thank you!
Is there a reason to prefer those two lines to just return str << std::setprecision(3) << std::fixed;? I mean functionally rather than stylistically.
@TartanLlama str is not a stream here, so this would not work I think.
@Holt Ah, right. I guess it would work if the function used std::ostream& instead, but that wouldn't be as generic?
@TartanLlama Yes you're right - I always forgot this one. The only advantage of the std::ios_base in this case is that it is more generic (you could make the yours a bit more generic but it would require a template). I also prefer std::ios_base because it is the one used by std::fixed and alike manipulator.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.