Search code examples
c++reflectionc++17if-constexpr

Does C++ 17 have static reflection?


Combining if constexpr with some <type_traits> entities, in C++17, I'm able to inspect types at compile time. Can these techniques be considered static reflection? Or is it just type inspection? Example:

if constexpr (std::is_same_v<T, U>) statement

Does the reflection concept apply only to runtime? Is right to call it static reflection?


Solution

  • Could is_same be considered a form of static reflection? It is in fact static, a compile-time detectable property of a type. And you can in fact write code that will execute based on introspecting this property. So technically, it is perfectly valid to call it "reflection".

    But if you're going to be useful with words, if you want to effectively use words to communicate, then you have to recognize that dictionary definitions aren't exactly useful. This is because people have different dictionaries, different expectations of what words mean. And words can change their meaning or have special meaning in different contexts. So if you're going to effectively communicate with people, you have to use words that will actually convey the meaning that you intend to communicate.

    In particular, the words "static reflection" in the context of C++ typically refer to functionality related to this proposal (PDF) (cleverly named "Static Reflection") and its many, many revisions. Specifically, if you make the claim that C++ has "static reflection" as some kind of language feature, then to many C++ users, you are making the claim that users can do things like enumerate properties about a class (like the member subobjects of a type) and iterate over them, performing some action on each such property.

    After all, that is what you can do in other languages that offer reflection as a first-class feature. "Reflection" is not just being able to ask if a given type is a particular type or if a given type satisfies a basic property. Reflection is about being able to introspect pretty much every facet of interest on a type.

    That's the expectation that the term "static reflection" gives many C++ programmers. When C++ programmers talk about wanting "static reflection", that is what they're saying that they want.

    So while you could technically claim that C++ already has "static reflection", it is not useful to make such a claim.