Accessing struct members with array subscript operator

后端 未结 5 1757
萌比男神i
萌比男神i 2021-01-07 10:49

Let have a type T and a struct having ONLY uniform elements of T type.

struct Foo {
    T one,
    T two,
    T three
};

I\'d like to acces

5条回答
  •  半阙折子戏
    2021-01-07 11:36

    You might be able to achieve what you want using an array to hold the data (so you can get indexed access without using a lookup table) and having references to the various array elements (so you can have 'named' elements for use by your macros).

    I'm not sure what your macros require, so I'm not 100% sure this will work, but it might. Also, I'm not sure that the slight overhead of the lookup table approach is worth jumping through too many hoops to avoid. On the other hand, I don't think the approach I suggest here is any more complex than the table-of-pointers approach, so here it is for your consideration:

    #include 
    
    template< typename T >
    struct Foo {
    
    private:    
        T data_[3];
    
    public:
    
        T& one;
        T& two;
        T& three;
    
        const T& operator[](size_t i) const {
            return data_[i];
        }
    
        T& operator[](size_t i) {
            return data_[i];
        }
    
        Foo() :
            one( data_[0]),
            two( data_[1]),
            three( data_[2])
            {};
    
    };
    
    
    int main()
    {
        Foo foo;
    
        foo[0] = 11;
        foo[1] = 22;
        foo[2] = 33;
    
        printf( "%d, %d, %d\n", foo.one, foo.two, foo.three);
    
        Foo const cfoo( foo);
    
        printf( "%d, %d, %d\n", cfoo[0], cfoo[1], cfoo[2]);
    
        return 0;
    }
    

提交回复
热议问题