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

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -