lefticus / cpp_weekly

The official C++ Weekly Repository. Code samples and notes of future / past episodes will land here at various times. PR's will be accepted in some cases.
The Unlicense
663 stars 24 forks source link

C++ Custom user defined attributes #383

Open baderouaich opened 1 month ago

baderouaich commented 1 month ago

Channel
C++Weekly

Topics

Since the C++ standard does not yet allow us to define our own attributes like [[metadata]], what are the alternatives to achieve this? Is it even possible?

Here's a use case where I wished C++ could have custom attributes. Imagine you want to create a SQL ORM library object User and mark its class members with specific metadata, such as User::id as the primary key and User::email as unique .. etc, using custom attributes such as:

struct User {
   [[primary_key]]              int id;
   [[unique]]                   std::string email;
   [[length(24)]]               std::string name;
   [[not_null]]                 std::string gender;
   [[check(between(18, 80))]]   int age;
};

Then, we could check if a class member has an attribute with something like this:

if constexpr (has_attribute(&User::id, "primary_key")) {
    ...
}
if constexpr (has_attribute(&User::name, "length")) {
    constexpr auto name_length = get_attribute_value(&User::name, "length");
    ...
}

After little research, I found that this can be achieved by modifying Clang's source code to handle custom attributes, but it's quite a task, really! Another approach is to use cppast to parse the C++ files with the attributes and generate additional C++ files before building.

I think this topic would be really fun to cover in an episode. The ability to create your own custom attributes and handle them at compile time is interesting.

Some useful resources on c++ custom attributes: