"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Can C++11 Achieve C#-Like Properties with Unnamed Classes and Lambdas?

Can C++11 Achieve C#-Like Properties with Unnamed Classes and Lambdas?

Published on 2024-11-03
Browse:453

 Can C  11 Achieve C#-Like Properties with Unnamed Classes and Lambdas?

C 11: Properties Like C#?

C# syntax allows for concise field getters and setters. C 11 introduces named classes and lambdas, offering a similar solution.

Implementing C# Properties in C 11

To emulate C# properties in C 11, you can employ unnamed classes and member access functions. Consider the following implementation:

struct Foo {
    struct {
        int value;
        auto &operator=(const int &i) -> decltype(auto) { return value = i; }
        auto operator()() const -> decltype(auto) { return value; }
    } alpha;

    struct {
        float value;
        auto &operator=(const float &f) -> decltype(auto) { return value = f; }
        auto operator()() const -> decltype(auto) { return value; }
    } bravo;
};

Usage Example

Foo foo;
foo.alpha = 10;
cout 

This approach provides a C#-like syntax for getting and setting properties with auto-generated names.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3