How to template'ize variable NAMES, not types?

前端 未结 4 1576
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:52

    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
    void doSomething(std::vector & 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.

提交回复
热议问题