开发者

Use templates as a members when not all the details are known

Is it possible to specifiy a template as a member but not know all the details? Or rather how can I work around this.

Example doesn't work but might show you what I'm trying to achieve.

template<typename T>
str开发者_StackOverflowuct Foo {
   ///blah...
};

struct Bar {
    Foo* m_foo;
};

Bar in this case is a base class, and depending on the derived classes I wont know the full details of Foo


You can either make Bar a template class as well so it can pass that template argument along to Foo, or else you can make all the Foo<T> variations inherit from a common interface (in C++, an interface is just an abstract class with no implementation, all members are pure virtual functions) and then Bar can point to that interface.

The first way is better if Bar is just going to provide some functionality which will be reused by a bunch of derived classes.

The second way is better if descendants of Bar are going to be used polymorphically.


The code you have above won't work, since whenever you use a C++ template you must specify what it's arguments are. If you want to store a Foo of an unknown type, you can do so by parameterizing Bar over some type (for example, making it a template with type argument T), then having Bar store a Foo. This contrasts with other languages like Java where code like what you have outlined above is legal because templates work differently in C++. In particular, Java-style genetics just compile down to one concrete representation, then use runtime checks to verify that they're being used properly. C++ template instantiations all end up getting compiled down into separate code, and so the compiler has to be able to infer at compile-time what the argument types are (so it knows what code to generate).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜