C ++ variable declared in function body but not member of class?

I want to create a C ++ class with the following type:

  • It can be declared inside a function.
  • It can be declared inside a member function.
  • It cannot be declared as a member of a class.

Usage of this: think of Root objects for the GC.

Is this possible in C ++? In particular, I am using g ++. I wish to switch to clang. Either the templates or the macro controller is excellent.

Thanks!

+6
c ++ variables declaration
source share
2 answers

You can do this with a macro, perhaps:

#define MY_TYPE \ do { } while(0); \ RealType void foo() { MY_TYPE myvar; myvar.Whatever(); } 

This will compile inside the function (due to the "do ... while" bit, although you will get a really strange error message). This seems to be one of those "evil" uses of macros that you would like to avoid, however ...

+16
source share

Although I should love the codeka answer, I can't help but imagine that the problem is with the declaration as a member attribute.

For something like GC-GC, I would probably use the Monoid pattern. All instances of the class are actually proxies of a Singleton (essentially), i.e. They all have the same state. Thus, no matter how many instances are created, they all point to the same resource.

If you do this to avoid circular references, I am afraid that this is not enough.

 struct A { boost::shared_ptr<B> mB; }; struct B { boost::shared_ptr<A> mA; }; 
0
source share

All Articles