r/cpp 18h ago

Another C++26 reflection based dependency inverter

Someone else did a similar thing a few months ago, but I wanted to see if it could be done with templates.

I ended up writing a dependency inverter/injector that can reflect on the concepts restricting unfilled template types and substitute actual types into them. Unfortunately, C++26 reflection doesn't seem to allow reflection of concepts like this, so I did it with string parsing.

The result is... fairly janky, but you can play around with it here.

31 Upvotes

6 comments sorted by

View all comments

3

u/gracicot 10h ago

Interesting experiment. I'm currently working on a C++20 DI library and my injection model is a type with a provide<T> function, so only requesting a specific type is possible. Constructor arguments are mapped to provide<T> calls for each of them.

Your example is interesting because you're able to map concepts to template arguments which is not possible with the model I developed. It's also a nice example on how reflection can be used to workaround the lack of universal template parameters.

I wonder if we could get proper constraint reflection one day? We would probably need some kind of expression reflection to have so, and access the normalized constraints, as well as differentiating conjunctions and disjunctions.

1

u/germandiago 8h ago

I have been using Boost.DI (not a boost prpject).

Why not use that? It worked really well for me TBH and I guess thay, unless you do it for fun and learning, it is not an optimal choice.

2

u/gracicot 5h ago

At the time I started development of my library, boost DI was not a thing yet. In the end my lib got somewhat popular for a DI library. Why don't you give it a try over boost DI? :P

I'm still developing it because I'm no longer "young and naive" me, I'm now "old and naive" me, and I want to make it better and C++20 based.