0

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?

TobiR
  • 207
  • 3
  • 11
  • 1
    some of those names are 4 characters long, how is anyone meant to know what `std::cout << w(10) << p(4) << l` is meant to be? – Caleth May 28 '21 at 10:00
  • 1
    readability is very subjective. I suggest you to leave that out of the quesiton. I agree with Caleth that introducing even shorter names or in general introducing aliases that are uncommon to the reader (while the reader does know `setw`, `setprecision` etc) is causing code to be unreadable rather than readable. However, the question boils down to "How to get an alias to iomanipulators?" and we need not enter opinion-based readability to answer that. – 463035818_is_not_an_ai May 28 '21 at 10:12
  • The problem with your intentions is that the end result will be code that only you can read. That only works only until you need others' help with your code. And they will not be able to read it and help you. Having an alias definition sitting on top of the file won't help. Visual recognition is crucial to quickly analyzing a section of a code. Experienced developers are hardwired to recognize standard library names, and won't be able to help you much if they only see a `w` or an `s`, sitting there, by themselves. – Sam Varshavchik May 28 '21 at 10:56
  • If you need to do a lot of formatting, consider using [`std::format`](https://en.cppreference.com/w/cpp/utility/format/format) instead. If you're not using C++20, then see if [`std::printf`](https://en.cppreference.com/w/cpp/io/c/fprintf) would work or look up some formatting library. – mediocrevegetable1 May 28 '21 at 11:03

1 Answers1

2

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.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185