c++ - template code returntype overload not compiling. whats wrong -


i trying following code overload simple function work multiple types. however, fails compile. can 1 please tell me whats wrong , how fix this?

typedef struct str1_type {     int f1;     int f2; } str1;  typedef struct str2_type {     char f1[100];     char f2[100]; }str2;  template <typename t1, typename t2> t2 getfieldoffset(const t1& t, int i);  int main() {      str1 str1;     str2 str2;      int = getfieldoffset(str1,0);      const char* test = getfieldoffset(str2,0);  }  template <typename t1, typename t2> t2 getfieldoffset(const t1& t, int i) {     switch (i) {         case 0:             return t.f1;         case 1:             return t.f2;         default:         {             cout << "invalid index passed: i" << << endl;             return null;         }     } } 

here error message:

test2.cpp: in function 'int main()':
test2.cpp:73: error: no matching function call 'getfieldoffset(str1&, int)'
test2.cpp:75: error: no matching function call 'getfieldoffset(str2&, int)'

test2.cpp: in function 't2 getfieldoffset(const t1&, int)':
test2.cpp:90: error: 'null' not declared in scope

template <typename t1, typename t2>  t2 getfieldoffset(const t1& t, int i);  

only template argument t1 can deduced arguments, have explicitly provide template argument t2 in template argument list when make call.

however, if use function template written, have provide arguments both template parameters. should swap positions of t1 , t2 in template parameter list have specify t2:

template <typename t2, typename t1>  t2 getfieldoffset(const t1& t, int i);    

or, better names template parameters:

template <typename treturn, typename t>  treturn getfieldoffset(const t& t, int i);   

now can call as:

getfieldoffset<returntype>(str1,0);  

Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -