To be short, I want to achieve something like “templatize” the operation of “getting an attribute of a object” as a generalized template function, like the function foo
below.
template <
typename T,
// something like
"attribute" obj // or T::obj
>
"sth refer to type of obj" foo(T t)
{
return t.obj;
}
What I hope to achieve is, with any simple struct/class like
struct A
{
int b;
type_of_c c;
...
} a; // for any class/struct A with (non-function) attribute b in any type
foo<A, A::b>(a)
may return a.b
, and foo<A, A::c>(a)
may return a.c
.
So my question is, how can I express T::obj
to set the information of “specifying attribute obj
of class T
” as the parameter of template?
Some limitations in my programming:
- Methods that unfriendly to compile and IDE auto-hints are not encouraged. e.g. sending attribute name in form of string instead of attribute itself, or involving macro.
- Add type of
T::obj
to the template is acceptable, but not encouraged. - Tricks in any version of c++ is acceptable. Using newly published versions like C++20 is definitely ok.
- The solution is expected to work also for class template, if possible.