优秀的编程知识分享平台

网站首页 > 技术文章 正文

C++每日一练(20210623):奇异递归模板模式之链式调用实现

nanyue 2024-09-02 19:03:49 技术文章 7 ℃

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

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

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

#include <iostream>

enum Color {RED, GREEN, BLUE};

// Base class
template <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 class
class ColorPrinter : public Printer<ColorPrinter> {
public:
    ColorPrinter() : Printer(std::cout) {}

    ColorPrinter& set_console_color(Color c) { 

        switch(c){
            case BLUE:
                    std::cout << "\033[0;1;34m";
                    break;
            case RED:
                    std::cout << "\033[0;1;31m";
                    break;
            case GREEN:
                    std::cout << "\033[0;1;32m";
                    break;
        }
        
        return *this;
    }
};

int main() {
    // usage
    ColorPrinter().print("Hello ").set_console_color(RED).println("World!");
}
https://wandbox.org/permlink/y0bsoW9S4JHnBrOu
https://wandbox.org/nojs/gcc-head
https://wandbox.org/nojs/clang-head

Tags:

最近发表
标签列表