2011-12-08 2 views
7

Tôi đang viết nhật ký. Nếu bị tắt, đây là mã xác định macro LOG:Dòng suối ruồi, tôi có phải bao gồm dòng trứng không?

#ifdef NO_LOG 

#include <ostream> 

struct nullstream : std::ostream { 
    nullstream() : std::ios(0), std::ostream(0) {} 
}; 

static nullstream logstream; 

#define LOG if(0) logstream 

#endif 

LOG << "Log message " << 123 << std::endl; 

Nó hoạt động chính xác. Trình biên dịch nên loại bỏ hoàn toàn mã liên quan đến macro LOG.

Tuy nhiên tôi muốn tránh sự bao gồm của ostream và xác định đối tượng logstream như một cái gì đó thực sự "ánh sáng", có thể null.

Cảm ơn bạn!

Trả lời

12
// We still need a forward declaration of 'ostream' in order to 
// swallow templated manipulators such as 'endl'. 
#include <iosfwd> 

struct nullstream {}; 

// Swallow all types 
template <typename T> 
nullstream & operator<<(nullstream & s, T const &) {return s;} 

// Swallow manipulator templates 
nullstream & operator<<(nullstream & s, std::ostream &(std::ostream&)) {return s;} 

static nullstream logstream; 

#define LOG if(0) logstream 

// Example (including "iostream" so we can test the behaviour with "endl"). 
#include <iostream> 

int main() 
{ 
    LOG << "Log message " << 123 << std::endl; 
} 
+0

Nó hoạt động, nhưng nó có thể tránh sự bao gồm của iostream? Ví dụ: có thể sử dụng cái gì khác thay vì std :: endl? –

+0

@Pietro: chỉ cần thiết cho ví dụ, cho 'std :: endl'. 'nullstream' không cần nó, chỉ cần' '(các khai báo chuyển tiếp của' 'loại). –

+0

@Pietro Thường thì có thể sử dụng '\ n' thay vì std :: endl. – UncleBens

5

Tại sao không thực hiện điều toàn bộ từ đầu:

struct nullstream { }; 

template <typename T> 
nullstream & operator<<(nullstream & o, T const & x) { return o; } 

static nullstream logstream; 
+2

Điều đó sẽ được 'nullstream' thay vì' std :: ostream'? – sth

+2

Bạn có nghĩa là 'nullstream & operator << (nullstream & o, T const & x)'? Và nó sẽ không hoạt động với 'endl'. – fefe

+0

@fefe: bạn đúng; endl dường như là vấn đề duy nhất, bây giờ. Có thể chấm dứt luồng theo cách khác không. Tôi thực sự muốn tránh sự bao gồm của ostream nếu tôi không cần đăng nhập ... –