Genericは難儀だ
何やらraytraceの下回りのライブラリをGeneric
にできそうな気がしたので試行錯誤していたのだが
途中まで作って値が全部コピーで非常に効率悪いのに気付く。
ここで、
pointerの時はコピーで他の型が来たらreference(場合によってはconst reference)
にテンプレートで振り分けられないかと思ってMPLとかtype_traits界隈を
探索してみた。
みたのだが、ちょっと今のスキルでは妥当な解決策になりそうになかったので撤退しつつ
なおもうろうろしていたらひとつ収穫があったのでメモ。
boost::refであります。
関数呼び出し時に値のコピーを回避するサンプル。
(構造体の方でref,crefをはがすとコピーになる)
#include <iostream> #include <typeinfo> //#include <tr1/functional> #include <boost/ref.hpp> template<typename T> void func(T _t) { typename boost::unwrap_reference<T>::type &t=_t; //std::cout << typeid(t).name() << std::endl; std::cout << &t << std::endl; std::cout << t[0] << ',' << t[1] << ',' << t[2] << std::endl; } // constで受けるサンプル template<typename T> void const_func(T _t) { const typename boost::unwrap_reference<T>::type &t=_t; //std::cout << typeid(t).name() << std::endl; std::cout << &t << std::endl; std::cout << t[0] << ',' << t[1] << ',' << t[2] << std::endl; } struct Vector3 { ~Vector3() { std::cout << "destruct" << std::endl; } float v[3]; float &operator[](const int index){ return v[index]; } const float &operator[](const int index)const{ return v[index]; } }; int main() { { // structure Vector3 v; v[0]=0.0f; v[1]=1.0f; v[2]=2.0f; std::cout << &v << std::endl; func(boost::ref(v)); const_func(boost::cref(v)); } std::cout << "--------------------" << std::endl; { // pointer float x[3]={0.0f, 1.0f, 2.0f}; func(x); const_func(x); } }
refはtr1のfunctionalにも収録されているのだがunwrap_referenceが無くなっている。
そもそもこれで使い方があっているのかは不明。
呼ぶ方の情報少しはあるのだけど、呼ばれる方の情報が皆無なのデス。