c++也能实现rust中的trait?
rust中trait约束类型非...
rust中trait约束类型非常好用,并且是真0开销抽象,没有虚表拖后腿
那么c++能不能实现呢?
以下是实现(如果约束不满足还能ide自动报错)
有请微软proxy库:
#include <iostream>
#include <sstream>
#include <proxy/proxy.h>
template <typename PROXY, typename T>
requires requires(T&& t) { pro::make_proxy<PROXY, T>(std::forward<T>(t)); }
auto to_proxy(T&& t) -> pro::proxy<PROXY> {
return pro::make_proxy<PROXY, T>(std::forward<T>(t));
}
PRO_DEF_MEM_DISPATCH(MemDraw, Draw);
PRO_DEF_MEM_DISPATCH(MemArea, Area);
struct DrawableProxy : pro::facade_builder
::add_convention<MemDraw, void(std::ostream& output) const>
::add_convention<MemArea, double() const noexcept >
::support_copy<pro::constraint_level::nontrivial>
::build {};
template <typename T>
concept DrawableConcept =
requires(const T& t, std::ostream& os) {
{ t.Draw(os) } -> std::same_as<void>;
{ t.Area() } -> std::convertible_to<double>;
};
这里定义了一个DrawableProxy,它几乎就是trait的运行时平替
但是介于c++特有的定义两遍才完整:
我们还定义了一个DrawableConcept来提供更好的编译时报错以及IDE自动报错
这样有了约束Drawable:
必须含有方法:
void Draw(std::ostream& out) const {
// ...
}
double Area() const noexcept { return /* ... */ ; }
那么有什么用?
class Rectangle {
public:
Rectangle(double width, double height) : width_(width), height_(height) {}
Rectangle(const Rectangle&) = default;
void Draw(std::ostream& out) const {
out << "{Rectangle: width = " << width_ << ", height = " << height_ << "}";
}
double Area() const noexcept { return width_ * height_; }
private:
double width_;
double height_;
};
class Circle {
public:
explicit Circle(double r) : r_(r) {}
Circle(const Circle&) = default;
void Draw(std::ostream& out) const {
out << "{Circle: r = " << r_ << "}";
}
double Area() const noexcept { return std::numbers::pi * r_ * r_; }
private:
double r_;
};
template <DrawableConcept T>
std::string PrintDrawableToString(T&& t) {
auto p = to_proxy<DrawableProxy>(t);
std::stringstream result;
result << "entity = ";
p->Draw(result);
result << ", area = " << p->Area();
return std::move(result).str();
}
int main() {
auto p = Rectangle(3, 5);
auto p1 = Circle(3);
std::string str = PrintDrawableToString(p);
std::string str2 = PrintDrawableToString(p1);
std::cout << str << "\n";
// "entity = {Rectangle: width = 3, height = 5}, area = 15"
std::cout << str2 << "\n";
// "entity = {Circle: r = 3}, area = 28.2743"
}
注意⚠️:这里的圆和矩形并没有什么继承关系
这样即使没有使用virtual虚函数也能通过我们的“trait”约束来实现多态