Curiously recurring template pattern: Difference between revisions

Content deleted Content added
Hayazin (talk | contribs)
Line 117:
{
public:
Printer(ostream& pstream) : m_stream(pstream) {}
template <typename T>
Printer& print(T&& t) { m_stream << t; return *this; }
template <typename T>
Printer& println(T&& t) { m_stream << t << endl; return *this; }
private:
ostream& m_stream;
};
</source>
Line 141:
{
public:
CoutPrinter() : Printer(cout) {}
 
CoutPrinter& SetConsoleColor(Color c)
{
// ...
return *this; }
}
};
</source>
Line 150 ⟶ 154:
 
<source lang="cpp">
// v----- we have a 'Printer' here, not a 'CoutPrinter'
CoutPrinter().print("Hello ").SetConsoleColor(Color.red).println("Printer!"); // compile error
</source>
Line 164 ⟶ 168:
{
public:
Printer(ostream& pstream) : m_stream(pstream) {}
template <typename T>
ConcretePrinter& print(T&& t)
{
m_stream << t;
return static_cast<ConcretePrinter&>(*this);
}
template <typename T>
ConcretePrinter& println(T&& t)
{
m_stream << t << endl;
return static_cast<ConcretePrinter&>(*this);
}
private:
ostream& m_stream;
};
Line 187 ⟶ 191:
{
public:
CoutPrinter() : Printer(cout) {}
CoutPrinter& SetConsoleColor(Color c)
{
// ...
return *this; }
}
};
// usage
CoutPrinter().print("Hello ").SetConsoleColor(Color.red).println("Printer!");
</source>