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.
簡單地說,就是可以通過名字調(diào)用函數(shù),訪問對象。而我們有一個對象,可以反推出其類型、成員/方法、成員/方法的類型。
很多編程語言都與該特性,如Java、Python
Method method = foo.getClass().getMethod("doSomething", null); method.invoke(foo, null);這里有簡單明了的解釋。
2. C++為什么沒有reflection
我的理解:reflection 需要編譯時保存類型定義信息,即使一個類型只定義而沒有使用,這將導(dǎo)致編譯后的文件過大,執(zhí)行速度變慢,與C++的設(shè)計理念不符。
stackoverflow上大佬說:
- ? 不是C++委員會工作的優(yōu)先事項,還有其他更高優(yōu)先級的事情要做;
- ? 大多數(shù)時候C++不需要使用refection, 不需要為不用的東西付出代價
- ? 編譯器需要保存所有定義的類型信息...
- ? 考慮C++中的模板, 每個特例都是一個單獨(dú)類型, 有時候模板類知道用到的時候才特例化,可能在運(yùn)行的時候不存在
3. C++有哪些實(shí)現(xiàn)refection的方法
即使C++語言標(biāo)準(zhǔn)不支持refection,也有一些tricky的方法能實(shí)現(xiàn)refection
如:
https://gracicot.github.io/reflection/2018/04/03/reflection-present.html
https://github.com/apolukhin/magic_get
4. 應(yīng)用舉例
獲取自定義結(jié)構(gòu)體的字段個數(shù)
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++ 有關(guān)鍵字std::typeid 操作符可以獲取一個(表達(dá)式)類型的信息。
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
總結(jié)
以上是生活随笔為你收集整理的C++ reflection/反射的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 南航C语言答案,2009-2011南航复
- 下一篇: qt geomery的单位是什么_生命吗