BigBrownBear00 BigBrownBear00 - 2 months ago 8
C++ Question

How to create an alias for multiple stream operations?

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 << "Hello world" << alias << std::endl;

Answer

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 dummy_alias {
    int n;
    dummy_alias(int n) : n(n) { }
};

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

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

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

Then:

std::cout << setalias(6) << 3.16464;