How to template'ize variable NAMES, not types?

前端 未结 4 1597
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:46

    I would use lambdas to solve this problem. Something like this:

    #include      // vector
    #include   // for_each
    #include  // function
    
    struct MyClass {
       void func1() const { std::cout << __FUNCTION__ << std::endl; }
       void func2() const { std::cout << __FUNCTION__ << std::endl; }
    };
    
    void doSomething(std::vector all, std::function f)
    {
       std::for_each(all.begin(), all.end(), f);
    }
    
    int main()
    {
       std::vector all;
       all.push_back(MyClass());
    
        // apply various methods to each MyClass:
       doSomething(all, [](MyClass& m) { m.func1(); });
       doSomething(all, [](MyClass& m) { m.func2(); });
    }
    

    Of course in this case the function doSomething is unnecessary. I could just as simply call for_each directly on all.

提交回复
热议问题