Re: [問題] template
※ 引述《yuchili》之銘言:
c++沒有聰明到會自己列出所有member
只能用暴力法
template<typename T, int T::* p1, int T::* p2> T NewElement() {
T t;
t.*p1 = rand();
t.*p2 = rand();
return t;
}
template<typename T> T NewElement() {}
template<> A NewElement<A>() {return NewElement<A, &A::a, &A::b>();}
template<> B NewElement<B>() {return NewELement<B, &B::s, &B::t>();}
int main() {
A a = NewElement<A>();
B b = NewElement<B>();
}
這樣做並不會比較爽 還不如用正常的方法寫XD
另外 用c++0x的Variadic templates可以寫出更暴力的東西:
struct A {int a, b, c;};
struct B {int s, t;}
template<class T> T NewElement() {
return T();
}
template<class T, int T::* p, int T::*... args> T NewElement() {
T t = NewElement<T, args...>();
t.*p = rand();
return t;
}
int main() {
NewElement<A, &A::a, &A::b, &A::c>();
NewELement<B, &B::s, &B::t>();
}
--
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 122.116.156.17
※ 編輯: Fenikso 來自: 122.116.156.17 (05/07 05:02)
→
05/07 12:39, , 1F
05/07 12:39, 1F
→
05/07 12:40, , 2F
05/07 12:40, 2F
討論串 (同標題文章)