2021年6月23日C++每日一练:掌握链式调用的奇异递归模板模式

发表时间: 2021-06-23 08:47

CRTP(Curiously recurring template pattern),奇异递归模板模式是C++模板编程时的一种惯用法:把派生类作为基类的模板参数。

链式调用是种语法糖,简化对一个对象的反复操作,并且阅读起来也很观。

obj.seta().setb().setc();

#include <iostream>enum Color {RED, GREEN, BLUE};// Base classtemplate <typename CustomPrinter>class Printer {public:    explicit Printer(std::ostream& pstream) : m_stream(pstream) {}    template <typename T>    CustomPrinter& print(T&& t)    {        m_stream << t;        return static_cast<CustomPrinter&>(*this);    }    template <typename T>    CustomPrinter& println(T&& t)    {        m_stream << t << std::endl;        return static_cast<CustomPrinter&>(*this);    }private:    std::ostream& m_stream;}; // Derived classclass ColorPrinter : public Printer<ColorPrinter> {public:    ColorPrinter() : Printer(std::cout) {}    ColorPrinter& set_console_color(Color c) {         switch(c){            case BLUE:                    std::cout << "3[0;1;34m";                    break;            case RED:                    std::cout << "3[0;1;31m";                    break;            case GREEN:                    std::cout << "3[0;1;32m";                    break;        }                return *this;    }};int main() {    // usage    ColorPrinter().print("Hello ").set_console_color(RED).println("World!");}

在线编译测试

https://wandbox.org/permlink/y0bsoW9S4JHnBrOuhttps://wandbox.org/nojs/gcc-headhttps://wandbox.org/nojs/clang-head