Live data from Hacker News

Implementing Rust-like traits for C++ 20 (with no runtime overhead)

news.ycombinator.com

1–2 of 2 posts

Implementing Rust-like traits for C++ 20 (with no runtime overhead)

#1
Example Code:

struct Shape {

    void draw();

    int area(int x, int y);  
};

make_trait(Shape, draw, area);

int main() {

    auto circle = Circle();
    auto square = Square();

    // NOTE: all of this is strictly checked, so if you are creating
    // a trait out of a Object, the object MUST implement all the trait functions


    auto t0 = trait::make(&circle);
    t0.draw();

    auto t1 = trait::make(&square);
    t1.draw();

    // Another thing to be kept in mind is trait is just like a View
    // It DOES NOT OWN anything, so you are the one making sure the data
    // pointer is valid
  
    auto array = std::array{t1, t0};
    for (auto& shape : array) {
        std::cout 
}

Repository: github.com/Jaysmito101/rusty.hpp?tab=readme-ov-file#traits-in-c