c++ - Generic method to apply operation on the given struct member -


i want implement generic method apply determined operation on struct member, passing member parameter. this:

typedef struct type_t{     int a;     double b; } type;  void gen_method(type &t, typemember m){     t.m += 1; } 

what i've done until now:

typedef struct type_t{     int a;     double b; } type;  typedef double type::* pointertotypememberdouble;  void gen_method(type &t, pointertotypememberdouble member){     t.*member += 1; } 

what want do

now want implement same generic method using templates allow user access struct member, independentrly of type. i've tested:

typedef struct type_t{     int a;     double b; } type;  template<typename t> struct pointertotypemember{     typedef t type::* type; };  template<typename t> void gen_method(type &t, pointertotypemember<t>::type member){     // ... } 

the error

when try compile, errors list: error c2061: syntax error : identifier 'type'

and warning: warning c4346: 'mynamespace::type<t>::type' : dependent name not type

firstly, error, need specify typename:

template<typename t> void gen_method(type &t, typename pointertotypemember<t>::type member) { 

see where , why have put “template” , “typename” keywords?

secondly, don't need helper class template pointertotypemember @ all. , because nested-name-specifier couldn't deduced in template argument deduction, have specify template argument when use as:

type t{}; gen_method<int>(t, &type::a); gen_method<double>(t, &type::b); 

you specify class member template parameter directly,

template<typename t> void gen_method(type &t, t type::*member){     t.*member += 1; } 

and no need specify template argument, template argument deduction you.

type t{}; gen_method(t, &type::a); gen_method(t, &type::b); 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -