How to template'ize variable NAMES, not types?

前端 未结 4 1593
Happy的楠姐
Happy的楠姐 2020-12-29 08:19

my question is about how to template\'ize the name of a class member that should be used.

Maybe a simplified & pseudo example:

4条回答
  •  天涯浪人
    2020-12-29 08:45

    sellibitze's solution is fine (though to be honest not very: see my edit), only it limits you to using only members of type int. A more general solution would be this (although the member is NOT a template parameter here)

    #include 
    
    struct MyClass
    {
       int i;
       char c;
    };
    
    template 
    void DoSomething(std::vector& all, T MyClass::* MemPtr)
    { 
       for(std::vector::size_type i = 0; i < all.size(); ++i)
          (all[i].*MemPtr)++;
    }
    
    int main()
    {
       std::vector all;
       DoSomething(all, &MyClass::i);
       DoSomething(all, &MyClass::c);
    }
    

    EDIT: Also please note that it is not generally a good idea for a pointer to member to be a template parameter inasmuch as only such pointers that are known compile-time can be passed, that is you can't determine the pointer runtime and then pass it as a template param.

提交回复
热议问题