Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an alias for multiple stream operations?

Tags:

c++

c++98

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;
like image 602
BigBrownBear00 Avatar asked Oct 03 '16 14:10

BigBrownBear00


1 Answers

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;
like image 92
Holt Avatar answered Nov 06 '22 08:11

Holt