Mixin技术学习笔记
Mixin(Mix in)是一种将若干个功能独立的类通过继承方式实现模块复用的C++模板编程技巧,其基本用法是将模板参数作为派生类基类,基本语法为:
template <typename... Mixins>
class MixinClass : public Mixins... {
public:
MixinClass() : Mixins...() {
}
// ...
};
Mixin
是一些列被称为 mixin
的类型,这些类型分别实现一个单独功能,且这些功能本身是正交的。当需要使用这些功能时,就可以将不同 mixin
组合在一起,像搭积木一样,完成功能复用。
#include <iostream>
template <typename... Mixins>
class Point : public Mixins... {
public:
Point(double x, double y) : Mixins()..., x_(x), y_(y) {}
Point() : Mixins()..., x_(0), y_(0) {}
~Point() = default;
[[nodiscard]] double x() const { return x_; }
[[nodiscard]] double y() const { return y_; }
void setX(double x) { x_ = x; }
void setY(double y) { y_ = y; }
private:
double x_;
double y_;
};
class Label {
public:
Label() : label_("default label") {}
~Label() = default;
void setLabel(const std::string& label) { label_ = label; }
[[nodiscard]] const std::string& label() const { return label_; }
private:
std::string label_;
};
class Color {
public:
Color() : red_(0), green_(0), blue_(0) {}
~Color() = default;
void setColor(double red, double green, double blue) {
red_ = red;
green_ = green;
blue_ = blue;
}
[[nodiscard]] const double &red() const { return red_; }
[[nodiscard]] const double &green() const { return green_; }
[[nodiscard]] const double &blue() const { return blue_; }
private:
double red_;
double green_;
double blue_;
};
using MyPoint = Point<Label, Color>;
int main() {
MyPoint p(1, 2);
p.setLabel("point");
p.setColor(1, 0, 0);
std::cout << "x: " << p.x() << std::endl;
std::cout << "y: " << p.y() << std::endl;
std::cout << "label: " << p.label() << std::endl;
std::cout << "red: " << p.red() << std::endl;
std::cout << "green: " << p.green() << std::endl;
std::cout << "blue: " << p.blue() << std::endl;
return 0;
}
输出结果:
x: 1
y: 2
label: point
red: 1
green: 0
blue: 0