my question is about how to template'ize the name of a class member that should be used.
Maybe a simplified & pseudo example:
/**
Does something with a specified member of every element in a List.
*/
template<membername MEMBER> // <-- How to define such thing?
void doSomething(std::vector<MyClass> all){
for( i=0; i < all.size(); i++)
all[i].MEMBER++; // e.g.; use all[i].MEMBER in same way
}
and
class MyClass{
public:
int aaa, bbb, ccc;
}
and the application:
main(){
vector<MyClass> all = ....
// applicate doSomething() to all aaa's
doSomething<aaa>(all); // or:
doSomething<MyClass::aaa>(all); // or:
doSomething<?????>(all);
}
How should the template definition looks like, that I can switch which member variable (aaa, bbb or ccc) of MyClass is accessed/modified in doSomething(.) ?
In my real world task all MEMBER are of same type, as above.
Thanks, Tebas
Template non-type arguments in C++It is also possible to use non-type arguments (basic/derived data types) i.e., in addition to the type argument T, it can also use other arguments such as strings, function names, constant expressions, and built-in data types.
A non-type template argument provided within a template argument list is an expression whose value can be determined at compile time. Such arguments must be constant expressions, addresses of functions or objects with external linkage, or addresses of static class members.
A variable template defines a family of variable (when declared at namespace scope) or a family of static data members (when defined at class scope).
Template specialization If we want to define a different implementation for a template when a specific type is passed as template parameter, we can declare a specialization of that template.
Template parameters are restricted to types, integer constants, pointers/references to functions or objects with external linkage and member pointers -- but no identifiers.
But you could use a member pointer as template parameter:
template<int MyClass::* MemPtr>
void doSomething(std::vector<MyClass> & all) {
for( i=0; i < all.size(); i++)
(all[i].*MemPtr)++;
}
:
doSomething<&MyClass::aaa>(all);
Note that I changed the doSomething function to take a reference instead of accepting the vector by value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With