Hacker News new | past | comments | ask | show | jobs | submit login
Implementing Rust-like traits for C++ 20 (with no runtime overhead)
3 points by jmax01 43 days ago | hide | past | favorite | 1 comment
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<Shape>::make(&circle);
    t0.draw();

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

    // Another thing to be kept in mind is trait<T> 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 << shape.area(2, 3) << std::endl;
    }    
}

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




How to inherit or extends a trait with another trait ?




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: