c++stlaliasfixedsetw

How to use a shorter name for `setw`, `setprecision`, `left`, `right`, `fixed` and `scentific`?


I would like to use these STL functions in my code, but so many times that their presence makes the readability of the code cumbersome. Is there any way to define "aliases" for these commands?


Solution

  • iomanipulators are functions and to most of them you can easily get a function pointer (actually I didn't check, but for example having several overloads or function templates, would make it less easy):

    #include <iostream>
    #include <iomanip>
    
    int main(){
        auto confu = std::setw;
        auto sing = std::setprecision;
        std::cout << confu(42) << sing(3) << 42;
    }
    

    I cannot help myself but to mention that your motivation is rather questionable. C++ programmers do know stuff from the standard library. The do not know your aliases. Hence for anybody but you readability will be decreased rather than improved. If you have complicated formatting you can wrap the printing in a function:

     my_fancy_print(42);
    

    Readers of C++ code are used to functions, they know where to look for their implementation and my_fancy_print(42) is not confusing, while std::cout << confu(42) << sing(3) << 42; is a source of surprise: I would have to look for definition of confu and sing just to realize that they are just aliases for something that could have been used directly.