Search code examples
c++classstructfunction-definitionmember-functions

Defining declared member function inside struct


struct a_t {
  struct not_yet_known_t;
  struct b_t {
    void f(not_yet_known_t* m);
  };
  struct c_t {
    b_t b;
    //...
  };
  struct not_yet_known_t {
    c_t c;
    //...
  };

  // ERROR HERE
  void b_t::f(not_yet_known_t* m) {
    // code comes here
  }
};

int main() {
  a_t::not_yet_known_t m;
  a_t::b_t b;
  b.f(&m);
}

Is it possible to define a_t::b_t::f inside a_t:: scope some way? Or if we could access global scope inside a_t:: but not actually pasting the code outside a_t:: scope?

Error I get:

main.cpp:16:13: error: non-friend class member 'f' cannot have a qualified name
  void b_t::f(not_yet_known_t* m) {
       ~~~~~^

Solution

  • struct a_t {
      struct not_yet_known_t;
      struct b_t {
        void f(not_yet_known_t* m){ _b_t_f(this, m); }
      };
      struct c_t {
        b_t b;
        //...
      };
      struct not_yet_known_t {
        c_t c;
        //...
      };
    
      static void _b_t_f(b_t* b, not_yet_known_t* m) {
        // code comes here
      }
    };
    

    Instead of declaring a_t::b_t::f you can define it to call another function then define that function in outside of a_t::b_t.

    You can use this way if you don't want to go outside of struct a_t. I suggest naming that function _b_t_f something like struct name + function name to be sure it will never collide with other things.