c++ - Template function on struct members -
is there way code single template function able run on different members of given struct
?
a wrong example :
struct foo { int a, b; } template <member x> //which not exist cout_member(foo foo) { cout << foo.x << endl; } int main() { foo foo; cout_member<a>(foo); cout_member<b>(foo); return 0; }
i imagined answer based on switch, wondered if switch tested on run-time (what avoid) or on compile-time ?
as long want pick data member set of data members having same type, can use pointer data member:
template <int foo::*m> void cout_member(foo foo) { std::cout << (foo.*m) << std::endl; }
and use as:
cout_member<&foo::a>(foo);
if want indicate type, can this:
template <typename t, t foo::*m> void cout_member(foo foo) { std::cout << (foo.*m) << std::endl; }
and use as:
cout_member<int, &foo::a>(foo);
just out of curiosity, second snippet simpler in c++17:
template <auto m> void cout_member(foo foo) { std::cout << (foo.*m) << std::endl; }
see , running on wandbox;
Comments
Post a Comment