Member pointer to array element

前端 未结 6 1218
野的像风
野的像风 2021-02-04 06:29

It\'s possible to define a pointer to a member and using this later on:

struct foo
{
  int a;
  int b[2];
};

int main() {
foo bar; int foo::*

6条回答
  •  隐瞒了意图╮
    2021-02-04 06:42

    You can't do that out of the language itself. But you can with boost. Bind a functor to some element of that array and assign it to a boost::function:

    #include 
    #include 
    #include 
    #include 
    
    struct test {
        int array[3];
    };
    
    int main() {
        namespace lmb = boost::lambda;
    
        // create functor that returns test::array[1]
        boost::function f;
        f = lmb::bind(&test::array, lmb::_1)[1];
    
        test t = {{ 11, 22, 33 }};
        std::cout << f(t) << std::endl; // 22
    
        f(t) = 44;
        std::cout << t.array[1] << std::endl; // 44
    }
    

提交回复
热议问题