C++ Logo

sg7

Advanced search

[SG7] Reflection Usecases

From: Jonathan O'Connor <jonathan.oconnor_at_[hidden]>
Date: Wed, 12 Jan 2022 15:57:53 +0000
Hi everyone,
I'm the new official Irish delegate on WG21, and I joined as I'm specifically interested in SG7.
I promised Matus Chochlik on twitter the other day that I would search for example reflection use cases in "Metaprogramming Ruby" by Paolo Perrotta. An email is more appropriate than multiple answers in twitter.
Sadly, and probably not surprisingly, I found few examples of reflection that are appropriate to C++.

The one trick that is used a lot in the Ruby on Rails framework is generating method code based on the name of the method. This trick is often used to generate SQL finders:

For example:
```ruby
User.findByName("Jonathan") # generates a SELECT * from users where name = 'Jonathan'
```
Converting this into C++ might require an interface class:

```c++
struct IUserTable : public MagicDBTable {
std::vector<User> findByName(std::string_view name);
};

// The getTable function generates an implementation of the IUserTable class that
// generates the appropriate select statement for each member function.
// It uses the class name to figure out the DB table name. The where clause is
// generated from the member function name.
auto userTable = MagicDB::getTableProxy<IUserTable>();
auto jonathans = userTable.findByName("Jonathan");
```

I'll leave Matus to do his mirror magic.

Regards,
Jonathan

Sent with [ProtonMail](https://protonmail.com/) Secure Email.

Received on 2022-01-12 15:57:59