- 論壇徽章:
- 44
|
回復(fù) 9# yulihua49
先不說(shuō)性能,只討論一下語(yǔ)法。
假設(shè)一個(gè)struct S:
- struct S {
- int m1;
- double m2;
- std::string m3;
- };
復(fù)制代碼 如果有一系列操作可以訪問(wèn)其成員,比如:
- S s;
- reflected<S>(s).set_attr("m1", 10);
- for(size_t i=0; i<reflected<S>::attr_count; i++) {
- std::cout << reflected<S>(s).attr_name(i) << ':' << reflected<S>(s).get_attr(i) << std::endl;
- }
復(fù)制代碼 這樣的話從功能上說(shuō)在大多數(shù)場(chǎng)合都?jí)蛴昧恕?br />
但上面這段代碼有一個(gè)問(wèn)題,reflected<T>::attribuet(...)的返回類(lèi)型無(wú)法確定,如果不想太hack的話,這個(gè)東西應(yīng)該返回一個(gè)variant之類(lèi)的東西,可以用來(lái)容納所有成員的類(lèi)型,比如針對(duì)上面的S返回類(lèi)型可以是variant<int, double, std::string>。
reflected這個(gè)模板無(wú)法用現(xiàn)有的C++語(yǔ)法實(shí)現(xiàn),我正在用libclang做一個(gè)code generator,可以針對(duì)特定的類(lèi)型T生成reflected<T>的特化版本,目前還未完工。
生成出來(lái)的reflected<S>大概是這個(gè)樣子的:
- template<>
- struct reflected<S> {
- static constexpr size_t attr_count=3;
- typedef std::tuple<int, double, std::string> attr_tuple_type;
- typedef std::tuple<int&, double&, std::string &> attr_accessor_tuple_type;
- typedef cxutil::variant<int, double, std::string> attr_variant_type;
- reflected(S &s)
- : accessor_(s.m1, s.m2, s.m3)
- {}
- void set_attr(size_t n, const attr_variant_type &v) { ... }
- void set_attr(const char *name, const attr_variant_type &v) { ... }
- attr_variant_type get_attr(size_t n) { ... }
- attr_variant_type get_attr(const char *name) { ... }
- constchar *attr_name(size_t n) { ... }
- private:
- attr_accessor_tuple_type accessor_;
- };
復(fù)制代碼 有了這個(gè)reflected<S>,做ORM的時(shí)候大概就可以這么寫(xiě)(假設(shè)Row::get也返回一個(gè)variant)
- template<typename T>
- void deserialize_from_db(T &t, Row row) {
- reflected<T> rt(t);
- for(size_t i=0; i<rt.attr_count; i++) {
- rt.set(i, row.get(i));
- }
- }
復(fù)制代碼 |
|