capture variables inside of subclass?
I was wondering something like this is possible. Perhaps using templates and trickery? The only rule right now i'll enforce is you are NOT ALLOWED to use a constructor in the class bar (so you cannot pass in a reference or pointer to foo nor a).
class Foo{
int a;
public:
struct Bar{
int barme(){ return a; }
};
};
I know one problem is how does bar know what instance of foo to use? i dont know but i'd like a foo to have many classes of Bar and more then one foo which each will have more then one bar.
I'm sure i seen a trick somewhere (maybe in a different language) but i dont know where. I do remember a template 开发者_开发知识库using compile time const but foo wont be compile time in this case although its ptr/ref could be
In C++ nested classes are just classes. It's not like Java where a nested class comes with an instance of the parent class along for the ride. Therefore, nothing like this is possible. You have to pass an instance of Foo
to operate on inside Bar
. (For example std::vector::iterator
does not come with a std::vector
-- it's a completely independent type)
Ask a weird question, get a weird answer (this is meant to be humerus and not a dig at you):
class Foo{
int a;
public:
struct Bar{
Foo* this_;
int barme(){ return this_->a; }
};
};
Look ma, no constructor!
Foo foo;
Foo::Bar bar = { &foo };
bar.barme();
you are NOT ALLOWED to use a constructor in the class bar (so you cannot pass in a reference or pointer to foo nor a).
But I just did! Or did you mean that I may not? Fine!
class Foo{
int a;
public:
static Foo* nothing_to_see_here;
Foo()
{ nothing_to_see_here = this; }
struct Bar{
int barme(){ return nothing_to_see_here->a; }
};
};
Look ma, no passing stuff!
Foo foo;
Foo::Bar bar;
bar.barme();
Or did you mean something akin to closures?
// C++0x up in this
#include <functional>
class Foo{
int a;
public:
std::function<int()>
bar()
{ return [=] { return a; }; }
};
No passing stuff in constructor or trickery* of any kind, guaranteed**!
Foo foo;
auto me = foo.bar();
me();
In C++ nesting one class inside another only means the name is nested, not that instances are nested. In other words, if you have classes A and B like:
class A {
class B {
// whatever
};
};
Then B being nested inside of A only affects the visibility of the names involved, not how instances of either can be/are created -- for example, you can create an A::B
without necessarily creating an instance of A
.
精彩评论