简体   繁体   中英

C++ ifdef for repeated lines

I have many printfs that I want to comment out and be able to uncomment in a flexible way again. I was thinking about solution like that:

#define SOMETHING
...

#ifdef SOMETHING
printf(....
#endif

but a weak part is I would have to do it for every printf. First question, does someone know any more efficient way? If so please give some snippet as an example, because with preprocessor and macrodefinitions I am a beginner.

Second question, can I do the same with couts , and if not, what would be a solution for them also?

You can accomplish this with a simple macro that allows you to completely remove the printf statements.

#ifdef PRINT_DATA
#define PRINT(x) printf x
#else
#define PRINT(x)
#endif


void test()
{
    PRINT(("Entering test\n"));
}

In addition to Caption Obvlious answer , since you were asking about std::cout : yes, this is possible, however, since you would use the << operator you have to provide a special nullstream which simply ignores every input:

#ifdef PRINT_DATA
#define OUT std::cout 
#else
#include <iosfwd> 
struct nullstream_t{};

template <typename T>
nullstream_t & operator<<(nullstream_t & s, T const &){return s;}
nullstream_t & operator<<(nullstream_t & s, std::ostream &(std::ostream&)){
    return s;
}

static nullstream_t nullstream;

#define OUT nullstream
#endif

#include <iostream>

int main(){
    OUT << "Hello World" << std::endl;
}

The idea is still a the same, you define a macro which either defines to std::cout or to a nullstream.

Selectively logging things is a problem that many have faced; instead of rolling your own solution and slowly expanding it as your requirements change, consider using an existing implementation like Boost.Log It has a ton of features that you might not need now, but may well need in the future.

For you question about cout, heres what I used:

#define verbose
//or
bool verbose = true;

//Verbose Output
#define VOUT(str) do { if (verbose) { std::cout << str; } } while (0,0)

The (0,0) was used to avoid some compiler warnings on Visual Studio. Using VOUT looks like this:

int i = 5;
VOUT("Hello world " << i << '\n');
//'Hello world 5
//'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM