Replace std::cout with a define - c++

I try to force my compiler to replace any std::cout occurrence in my code with something.
But when I write something like that:
#define std::cout (*some code*)
My compiler spit on my face. Is there a way to do this ?
EDIT :
Here is the code snippet:
# define std::cout (std_out << std::cout)
(std_out is a file I've previously open)
and the error on a line with a std::out occurence
the global scope has no "cout"

You define an identifier, not an arbitrary expression. std is
an identifier; your define will cause the compiler to replace
every instance of the identifier std with ::cout (*some
code*). So it's not surprising that the compiler doesn't like
it: std::cout << toto becomes ::cout (*some code*)::cout <<
toto and std::vector becomes ::cout (*some code*)::vector.
If you'd explain what you're actually trying to achieve, we could probably help you better.

I try to force my compiler to replace any std::cout occurence in my code with something
That's a bad idea. If you are looking for configurable behavior on your output stream, replace all occurrences of std::cout in your code with out, and declare out as std::ostream& out (= whatever stream type you may need).
My compiler spit on my face. Is there a way to do this ?
Not as such. No. You could write:
#define OUTPUT std::cout
OUTPUT << "a = " << a << std::endl;
but you needing a #define to disable (or redirect) your output stream is a sign of bad design (i.e. your define is not the problem you should be trying to solve).

You can make your own version of cout, that actually calls cout, you can place any custom code there:
std::ostream& my_cout() {
/// ...
return std::cout << "a custom message";
}
int main() {
my_cout() << " hi" << std::endl;
}

Related

How to use Macros in c++?

Recently I came across inline in c++17 and how it been used as an alternative to #define but both have its downsides. However my question is that if I want to cramp the whole std::cout << x << '\n'; in one simple line called LOG(x).
A: What should I use and why?
B: What are the pros and cons of each and when to use what?
1.)
#define LOG(x) std::cout << x << '\n'
2.)
void inline LOG(auto x)
{
std::cout << x << '\n';
}
3.)
void LOG(auto x)
{
std::cout << x << '\n';
}
4.)
This one was suggested to me by someone:
template <typename T>
void log(const T& x)
{
std::cout << x << '\n';
}
How to use Macros in c++?
Sparingly. When there is no better alternative.
Avoid this. Macros names don't respect scoping rules and thus are much more susceptible to name clashes. Also, consider what happens if you wanted to log a number bitshifted by another number:
LOG(0x1 << 2);
What output would you expect, and what output do you get? Do they match?
Pro: It is a function (template) and thus doesn't have the problems associated with macros. Con: You accept the parameter by value. This can be expensive with for example strings which are quite often used for logging. Requires C++20.
Practically identical to 2. The auto parameter turns these into function templates which are implicitly inline.
Pro: Doesn't require C++20. A reference is passed, which is good for passing strings.
In conclusion: 4. is a reasonable default choice.
The general consensus is that using macros is not a good idea. BUT what that really means is that ABUSE of macros is not a good idea.
Solution #2 is OK, but its usefulness is rather limited, since you can only print one value per line.
inline void LOG(const auto& x)
{
std::cout << x << '\n';
}
// use as:
LOG(x);
And it's an OK solution, but its usage is rather limited.. Consider this use case:
inline void LOG(const auto& x)
{
std::cout << x << '\n';
}
struct point { float x, y; };
// usability is kind of limited, since it will only print one value per line
point p{};
LOG(x);
LOG(y);
// which gives this output.
0
0
// That's not really useful for a log.
One advantage of the macro, is that you could make your log output a bit more useful.
#define LOG(x) std::cout << x << '\n'
struct point { float x, y; };
// usability is better, but still limited,
point p{};
LOG("x: " << p.x << ", y: " << p.y);
// which gives this output.
x: 0, y: 0
That's a bit better, you are using a macro, and you do have more control over the output, making your log more useful. But it puts some limitations on your code... For example, you may want, at a later date, to use a third party logging library, or write your own, but some calls to LOG() will have operators in them, and this may force you to rewrite them.
For this reason, among others, a function template would be better, one that accepts any number of arguments.
template <typename... Args>
inline void LOG(Args&&... args)
{
(std::cout << ... << args) << '\n';
}
point p{};
LOG("x: ", p.x, ", y: ", p.y);
// which gives this output.
x: 0, y: 0
If you want to defeat logging in your release version, I suggest using a macro.
#define LOG(...)
// on MSVC
#define LOG(...) __noop
I wouldn't use #1 (macro version) unless you want to log the symbol name of the variable in the output, such as:
#define LOG(x) std::cout << #x << " = " << x << '\n'
I believe #2 and #4 are equivalent, as using auto introduces a template type under the hood.
#3 is slightly inferior as it requires you to write a declaration in a header file as well as putting the definition in a source file (since it is not inline), which is more code to maintain.

Define variable type

I'm trying to convert a working define which prints the argument into a proper function, but I'm unsure of the variable type.
The working method I have is:
#define WARN(x) std::cout << "WARNING! " << x << "!" << std::endl;
Which I can then pass a sentence similar to using std::cout
WARN("This is a test warning." << " And this is some more stuff...");
However, I feel this should be more neatly wrapped into a function rather than using a define.
Please could you help me understand how the preprocessor is interpreting the variable x, and how I can translate the define into a function.
P.S. I am aware that I could use a variadic function, but I'd rather not have to pass the number of arguments and would rather avoid variadic altogether anyway.
but I'm unsure of the variable type.
That's where use of function templates can provide a clean solution.
template <typename T>
void WARN(T const& x)
{
std::cout << "WARNING! " << x << "!" << std::endl;
}
is a good replacement for
#define WARN(x) std::cout << "WARNING! " << x << "!" << std::endl;

Overloading streaming on the Arduino

Please RTFM me if needed, as so far I may have been searching for the wrong things!
On the Arduino
Serial << "sdf" << var;
works a treat (with streaming.h referenced), but
#if (CRIPWEB_DEBUG_BITS & DEBUG_CMD)
Serial << F("Run Macro: ") << strMacro << "\n";
#endif
takes three lines and makes the code unreadable.
I'd like to say something along the lines of:
Debug(CRIPWEB_DEBUG_BITS & DEBUG_CMD) << F("Run Macro: ") << strMacro << "\n";
Is this possible? I'd be happier with:
Debug.set(CRIPWEB_DEBUG_BITS & DEBUG_CMD); Debug << F("Run Macro: ") << strMacro << "\n";
I'll worry about size after I've had a go at this!
Many thanks,
Glyn
The preprocessor would be compile-time, the other would not. You really want the slowdown?
Anyway, if you accept a slightly different syntax, we get pretty near to what you wanted while not giving up on eliminating the useless code at compile-time:
#define COND(cond, ...) ((void)((exp) && (__VA_ARGS__, 0)))
Use as
COND(CRIPWEB_DEBUG_BITS & DEBUG_CMD, Serial << F("Run Macro: ") << strMacro << "\n");
Or, if you only ever test that one condition:
#define IFDEBUG(...) ((void)((CRIPWEB_DEBUG_BITS & DEBUG_CMD) && (__VA_ARGS__, 0)))
Use as
IFDEBUG(Serial << F("Run Macro: ") << strMacro << "\n");
You could write your own class to do exactly that.
I am answering only compile-time solution for the expression:
Serial << "sdf" << var;
Assume Serial is a global instance of class. Let's say instance of class DebugWriter. This class has overloaded operator <<. Now, you can make another class FakeDebugWriter, which will also have operator << implemented, but that would do nothing. Further, you can declare Serial instance as:
#if CRIPWEB_DEBUG_BITS & DEBUG_CMD
DebugWriter Serial;
#else
FakeDebugWriter Serial;
#endif
But it should be noted that Serial<< will still make call to function in case of FakeDebugWriter - though compiler may omit out the function call.
Therefore, it would be better to write debug-logging as function-style macro only. You can craft the macro has do some thing (or something heavy), and another as Do-nothing.
EDIT: After comment from OP. Here is analogues similar example.
SmallInt a, b;
Where SmallInt would be type-defined, depending on value(s) of pre-processor macro (not macro macro).
#if SomeCondition
typedef int SmallInt;
#else
typedef short SmallInt;
#endif

Why can't I add to a ostringstream outside a method/function

If I use this code outside of a method or winmain:
ostringstream vertexid;
vertexid << "bob";
vertexid << " ";
vertexid << " ";
vertexid << 48348093490;
I get all sorts of syntax errors. How does scope play into this why is this happening?
You can do something like this:
std::ostringstream ss;
#define nil(x) ((x), 0)
int x = nil(ss << "Hello");
int y = nil(ss << ", World!");
int z = nil(ss << std::endl);
If you really don't like thinking up variable names, then you can do something even crazier:
#define nilPASTE(x, y) x ## y
#define nilPASTE2(x, y) nilPASTE(x, y)
#define nil2(x) static int nilPASTE2(line_, __LINE__) = nil(x)
nil2(ss << "Goodbye");
nil2(ss << ", Sun!");
nil2(ss << std::endl);
You asked:
How does scope play into this why is this happening?
I assume you mention scope because that is what some error message spat out. But the answer to both parts of that question is that the C++ compiler is following the rules of the C++ language, which does not allow statements to just appear anywhere. They can only appear where they are allowed, which are in functions and method bodies. The reason my technique is allowed is because I am using expressions, and expressions can appear in more places. In particular, they are allowed to appear in an initializer to a variable. And of course, variable declarations are allowed on the outer most level of a translation unit.
All that gobbly gook means: put your statements inside functions and methods.
You can only declare or define stuff at global scope.
The first line alone would be OK (in an implementation file... if in a header, you risk having multiple definitions and would need to declare it as extern instead of defining it), the next lines are just not legal.
At global namespace you cannot have code, because when should it be executed? You can only put executable statements inside functions, for example WinMain/main.
The execution starts at WinMain/main, then you can call your other functions from there.

Converting bool to text in C++

Maybe this is a dumb question, but is there any way to convert a boolean value to a string such that 1 turns to "true" and 0 turns to "false"? I could just use an if statement, but it would be nice to know if there is a way to do that with the language or standard libraries. Plus, I'm a pedant. :)
How about using the C++ language itself?
bool t = true;
bool f = false;
std::cout << std::noboolalpha << t << " == " << std::boolalpha << t << std::endl;
std::cout << std::noboolalpha << f << " == " << std::boolalpha << f << std::endl;
UPDATE:
If you want more than 4 lines of code without any console output, please go to cppreference.com's page talking about std::boolalpha and std::noboolalpha which shows you the console output and explains more about the API.
Additionally using std::boolalpha will modify the global state of std::cout, you may want to restore the original behavior go here for more info on restoring the state of std::cout.
We're talking about C++ right? Why on earth are we still using macros!?
C++ inline functions give you the same speed as a macro, with the added benefit of type-safety and parameter evaluation (which avoids the issue that Rodney and dwj mentioned.
inline const char * const BoolToString(bool b)
{
return b ? "true" : "false";
}
Aside from that I have a few other gripes, particularly with the accepted answer :)
// this is used in C, not C++. if you want to use printf, instead include <cstdio>
//#include <stdio.h>
// instead you should use the iostream libs
#include <iostream>
// not only is this a C include, it's totally unnecessary!
//#include <stdarg.h>
// Macros - not type-safe, has side-effects. Use inline functions instead
//#define BOOL_STR(b) (b?"true":"false")
inline const char * const BoolToString(bool b)
{
return b ? "true" : "false";
}
int main (int argc, char const *argv[]) {
bool alpha = true;
// printf? that's C, not C++
//printf( BOOL_STR(alpha) );
// use the iostream functionality
std::cout << BoolToString(alpha);
return 0;
}
Cheers :)
#DrPizza: Include a whole boost lib for the sake of a function this simple? You've got to be kidding?
C++ has proper strings so you might as well use them. They're in the standard header string. #include <string> to use them. No more strcat/strcpy buffer overruns; no more missing null terminators; no more messy manual memory management; proper counted strings with proper value semantics.
C++ has the ability to convert bools into human-readable representations too. We saw hints at it earlier with the iostream examples, but they're a bit limited because they can only blast the text to the console (or with fstreams, a file). Fortunately, the designers of C++ weren't complete idiots; we also have iostreams that are backed not by the console or a file, but by an automatically managed string buffer. They're called stringstreams. #include <sstream> to get them. Then we can say:
std::string bool_as_text(bool b)
{
std::stringstream converter;
converter << std::boolalpha << b; // flag boolalpha calls converter.setf(std::ios_base::boolalpha)
return converter.str();
}
Of course, we don't really want to type all that. Fortunately, C++ also has a convenient third-party library named Boost that can help us out here. Boost has a nice function called lexical_cast. We can use it thus:
boost::lexical_cast<std::string>(my_bool)
Now, it's true to say that this is higher overhead than some macro; stringstreams deal with locales which you might not care about, and create a dynamic string (with memory allocation) whereas the macro can yield a literal string, which avoids that. But on the flip side, the stringstream method can be used for a great many conversions between printable and internal representations. You can run 'em backwards; boost::lexical_cast<bool>("true") does the right thing, for example. You can use them with numbers and in fact any type with the right formatted I/O operators. So they're quite versatile and useful.
And if after all this your profiling and benchmarking reveals that the lexical_casts are an unacceptable bottleneck, that's when you should consider doing some macro horror.
This should be fine:
const char* bool_cast(const bool b) {
return b ? "true" : "false";
}
But, if you want to do it more C++-ish:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string bool_cast(const bool b) {
ostringstream ss;
ss << boolalpha << b;
return ss.str();
}
int main() {
cout << bool_cast(true) << "\n";
cout << bool_cast(false) << "\n";
}
C++20 std::format("{}"
https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification claims that the default output format will be the string by default:
#include <format>
auto s6 = std::format("{:6}", true); // value of s6 is "true "
and:
The available bool presentation types are:
none, s: Copies textual representation (true or false, or the locale-specific form) to the output.
b, B, c, d, o, x, X: Uses integer presentation types with the value static_cast(value).
The existing fmt library implements it for before it gets official support: https://github.com/fmtlib/fmt Install on Ubuntu 22.04:
sudo apt install libfmt-dev
Modify source to replace:
<format> with <fmt/core.h>
std::format to fmt::format
main.cpp
#include <string>
#include <iostream>
#include <fmt/core.h>
int main() {
std::string message = fmt::format("The {} answer is {}.", true, false);
std::cout << message << std::endl;
}
and compile and run with:
g++ -std=c++11 -o main.out main.cpp -lfmt
./main.out
Output:
The true answer is false.
Related: std::string formatting like sprintf
If you decide to use macros (or are using C on a future project) you should add parenthesis around the 'b' in the macro expansion (I don't have enough points yet to edit other people's content):
#define BOOL_STR(b) ((b)?"true":"false")
This is a defensive programming technique that protects against hidden order-of-operations errors; i.e., how does this evaluate for all compilers?
1 == 2 ? "true" : "false"
compared to
(1 == 2) ? "true" : "false"
I use a ternary in a printf like this:
printf("%s\n", b?"true":"false");
If you macro it :
B2S(b) ((b)?"true":"false")
then you need to make sure whatever you pass in as 'b' doesn't have any side effects. And don't forget the brackets around the 'b' as you could get compile errors.
Without dragging ostream into it:
constexpr char const* to_c_str(bool b) {
return
std::array<char const*, 2>{"false", "true "}[b]
;
};
With C++11 you might use a lambda to get a slightly more compact code and in place usage:
bool to_convert{true};
auto bool_to_string = [](bool b) -> std::string {
return b ? "true" : "false";
};
std::string str{"string to print -> "};
std::cout<<str+bool_to_string(to_convert);
Prints:
string to print -> true
A really quick and clean solution, if you're only doing this once or don't want to change the global settings with bool alpha, is to use a ternary operator directly in the stream, like so:
bool myBool = true;
std::cout << "The state of myBool is: " << (myBool ? "true" : "false") << std::endl;
enter code here
Ternarys are easy to learn. They're just an IF statement on a diet, that can be dropped pretty well anywhere, and:
(myBool ? "true" : "false")
is pretty well this (sort of):
{
if(myBool){
return "true";
} else {
return "false";
}
}
You can find all kinds of fun uses for ternarys, including here, but if you're always using them to output a "true" "false" into the stream like this, you should just turn the boolalpha feature on, unless you have some reason not to:
std::cout << std::boolalpha;
somewhere at the top of your code to just turn the feature on globally, so you can just drop those sweet sweet booleans right into the stream and not worry about it.
But don't use it as a tag for one-off use, like this:
std::cout << "The state of myBool is: " << std::boolalpha << myBool << std::noboolalpha;
That's a lot of unnecessary function calls and wasted performance overhead and for a single bool, when a simple ternary operator will do.
This post is old but now you can use std::to_string to convert a lot of variable as std::string.
http://en.cppreference.com/w/cpp/string/basic_string/to_string
Use boolalpha to print bool to string.
std::cout << std::boolalpha << b << endl;
std::cout << std::noboolalpha << b << endl;
C++ Reference
How about the simple:
constexpr char const* toString(bool b)
{
return b ? "true" : "false";
}
#include <iostream>
#include <string>
using namespace std;
string toBool(bool boolean)
{
string result;
if(boolean == true)
result = "true";
else
result = "false";
return result;
}
int main()
{
bool myBoolean = true; //Boolean
string booleanValue;
booleanValue = toBool(myBoolean);
cout << "bool: " << booleanValue << "\n";
}
I agree that a macro might be the best fit. I just whipped up a test case (believe me I'm no good with C/C++ but this sounded fun):
#include <stdio.h>
#include <stdarg.h>
#define BOOL_STR(b) (b?"true":"false")
int main (int argc, char const *argv[]) {
bool alpha = true;
printf( BOOL_STR(alpha) );
return 0;
}
As long as strings can be viewed directly as a char array it's going to be really hard to convince me that std::string represents strings as first class citizens in C++.
Besides, combining allocation and boundedness seems to be a bad idea to me anyways.
Try this Macro. Anywhere you want the "true" or false to show up just replace it with PRINTBOOL(var) where var is the bool you want the text for.
#define PRINTBOOL(x) x?"true":"false"