c++ - Template specialization class function -
so have class use data structure, want 1 of functions in class behave differently if class storing pointers. want instead of returning pointer want return reference object when []
operator called.
this class before
template <typename t> class collectiontemplate { t ** obitems; //other code inline t& operator[](int iindex) { return * obitems[iindex]; } };
i add or this. code out side class
template<> classa & collectiontemplate<classa*>::operator[](int iindex) { return *(*obitems[iindex]); }
but error when run code
e2428 templates must classes or functions
from have read have seen people function templates not class templates idea on how awesome.
you can delegate type detection (pointer/reference) function shown below.
edit: static
before access
not matter since access
functions inlined anyway. removed again.
#include <vector> #include <iostream> template <class c> struct container { template <class t> t& access(t& x) { return x; } template <class t> t& access(t* x) { return *x; } std::vector<c> m_v; decltype(access(c)) operator [] (size_t i) { return access(m_v[i]); } }; int main() { int i1=1, i2=2; container<int*> cp; cp.m_v.push_back(&i1); cp.m_v.push_back(&i2); std::cout << "ip1=" << cp[0] << "\nip2=" << cp[1]; container<int> ci; ci.m_v.push_back(i1); ci.m_v.push_back(i2); std::cout << "\ni1=" << ci[0] << "\ni2=" << ci[1]; return 0; } /** local variables: compile-command: "g++ -std=c++11 test.cc -o a.exe && ./a.exe" end: */
Comments
Post a Comment