1. 先看一下什么叫reflecton
wiki上的定义: In computer science, reflection is the ability of a process to examine, introspect, and modify its own structure and behavior.
简单地说,就是可以通过名字调用函数,访问对象。而我们有一个对象,可以反推出其类型、成员/方法、成员/方法的类型。
很多编程语言都与该特性,如Java、Python
Method method = foo.getClass().getMethod("doSomething", null);
method.invoke(foo, null);
这里有简单明了的解释。
2. C++为什么没有reflection
我的理解:reflection 需要编译时保存类型定义信息,即使一个类型只定义而没有使用,这将导致编译后的文件过大,执行速度变慢,与C++的设计理念不符。
stackoverflow上大佬说:
- 不是C++委员会工作的优先事项,还有其他更高优先级的事情要做;
- 大多数时候C++不需要使用refection, 不需要为不用的东西付出代价
- 编译器需要保存所有定义的类型信息...
- 考虑C++中的模板, 每个特例都是一个单独类型, 有时候模板类知道用到的时候才特例化,可能在运行的时候不存在
3. C++有哪些实现refection的方法
即使C++语言标准不支持refection,也有一些tricky的方法能实现refection
如:
https://gracicot.github.io/reflection/2018/04/03/reflection-present.html
https://github.com/apolukhin/magic_get
4. 应用举例
获取自定义结构体的字段个数
template <class T, std::size_t I0, std::size_t... I>
constexpr auto detect_fields_count(std::size_t& out, std::index_sequence<I0, I...>)
-> decltype( T{ ubiq_constructor<I0>{}, ubiq_constructor<I>{}... } )
{ out = sizeof...(I) + 1; /*...*/ }
template <class T, std::size_t... I>
constexpr void detect_fields_count(std::size_t& out, std::index_sequence<I...>) {
detect_fields_count<T>(out, std::make_index_sequence<sizeof...(I) - 1>{});
}
C++ 有关键字std::typeid 操作符可以获取一个(表达式)类型的信息。
Ref:
https://en.wikipedia.org/wiki/Reflection_(computer_programming)
https://www.quora.com/What-does-reflection-in-a-programming-language-mean-in-simple-words
https://stackoverflow.com/questions/359237/why-does-c-not-have-reflection/359462