I have this sample block of code:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main(){
string blank = " ";
cout << "Hello" << blank << "47";
}
I have a lot of cout's of this type in my original code. I want to be able to change the blank string to setw(2) function without having to replace blank with setw(2) on each and every cout I have in my code. So is there a way to set a cpp function to a variable? So I can call the function by typing the name? for example:
func blank = setw(2);
cout<< "Hello" << blank << "47";
The type of std::setw(x) is unspecified, but you don't need to know it.
You can just use auto:
auto blank = std::setw(2);
As @StoryTeller noted, while this should work on sane implementations, it's not guaranteed to.
A safer option would be to make a class with overloaded <<:
struct blank_t {} blank;
std::ostream &operator<<(std::ostream &s, blank_t)
{
return s << std::setw(2);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With