C++ reflection/反射
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
總結
以上是生活随笔為你收集整理的C++ reflection/反射的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 南航C语言答案,2009-2011南航复
- 下一篇: s3c2440移植MQTT