क्या मैं कर रहा सिफारिश करेंगे एक वर्ग है जो इस तरह एक iostream इर्द-गिर्द घूमती चल रहा है: तो फिर
#include <iostream>
#define LOG Log()
class Log
{
public:
Log(){}
~Log()
{
// Add an newline.
std::cout << std::endl;
}
template<typename T>
Log &operator << (const T &t)
{
std::cout << t;
return * this;
}
};
, जब भी आप जहां डाटा चला जाता है बदलना चाहते हैं, तो आप सिर्फ वर्ग व्यवहार को बदलने। का तरीका यहां बताया वर्ग का उपयोग करें:
LOG << "Use this like an iostream.";
[संपादित करें] आलू swatter के रूप में सुझाव दिया है, मैं अदालत के अलावा कुछ के साथ एक उदाहरण जोड़ देंगे:
#include <sstream>
#define LOG Log()
// An example with a string stream.
class Log
{
private:
static std::stringstream buf;
public:
Log(){}
~Log()
{
// Add an newline.
buf << std::endl;
}
template<typename T>
Log &operator << (const T &t)
{
buf << t;
return * this;
}
};
// Define the static member, somewhere in an implementation file.
std::stringstream Log::buf;
कारण है कि आप की कोशिश करनी चाहिए का सवाल है यह एक स्ट्रिंग स्ट्रीम की तरह कुछ से विरासत के बजाय, मुख्य रूप से क्योंकि आप आसानी से बदल सकते हैं जहां लॉगर गतिशील रूप से आउटपुट करता है। उदाहरण के लिए, आप तीन अलग-अलग उत्पादन स्ट्रीम नहीं है, और रनटाइम पर के बीच स्वैप करने के लिए एक स्थिर सदस्य चर इस्तेमाल कर सकते हैं:
class Log
{
private:
static int outputIndex = 0;
// Add a few static streams in here.
static std::stringstream bufOne;
static std::stringstream bufTwo;
static std::stringstream bufThree;
public:
// Constructor/ destructor goes here.
template<typename T>
Log &operator << (const T &t)
{
// Switch between different outputs.
switch (outputIndex)
{
case 1:
bufOne << t;
break;
case 2:
bufTwo << t;
case 3:
bufThree << t;
default:
std::cout << t;
break;
}
return * this;
}
static void setOutputIndex(int _outputIndex)
{
outputIndex = _outputIndex;
}
};
// In use
LOG << "Print to stream 1";
Log::setOutputIndex(2);
LOG << "Print to stream 2";
Log::setOutputIndex(3);
LOG << "Print to stream 3";
Log::setOutputIndex(0);
LOG << "Print to cout";
यह आसानी से प्रवेश से निपटने का एक शक्तिशाली तरीका बनाने के लिए विस्तारित किया जा सकता। आप filestreams जोड़ सकता है, std :: cerr, आदि
स्रोत
2011-08-24 00:42:49
सी ++ "रूपों" नहीं है। –
ठीक है, मेरा मतलब कुछ दृश्य है, कंसोल – Bakudan
नोट नहीं, जो आमतौर पर स्ट्रीमिंग व्यवहार को ओवरराइड करना std :: streambuf इंटरफेस को कार्यान्वित करके किया जाता है। यह अपेक्षाकृत जटिल कार्य है, इसलिए आपको शायद प्रदान किए गए अन्य उत्तरों का उपयोग करना चाहिए। – Basilevs