Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to template'ize variable NAMES, not types?

Tags:

c++

templates

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

like image 914
Tebas Avatar asked Oct 15 '10 12:10

Tebas


People also ask

Can we pass non-type parameters to templates?

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.

What is non-type argument?

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.

What is a variable template?

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).

How can you define an implementation of a template when a specific type is passed as template parameter?

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.


1 Answers

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.

like image 145
sellibitze Avatar answered Oct 14 '22 15:10

sellibitze