开发者

Forward-declaring library names

An excerpt from "Exceptional C++":

"In the old days, you could just replace "#include " with "class ostream;" in this situation, because ostream used to be a class and it wasn't in namespace std. Alas, no more. Writing "class ostream;" is illegal for two reasons:

ostream is now in namespace std, and programmers aren't allowed to declare anything that lives in namespace std.

开发者_运维知识库

ostream is now a typedef of a template; specifically, it's typedef'd as basic_ostream. Not only would the basic_ostream template be messy to forward-declare in any case, but you couldn't reliably forward-declare it at all, because library implementations are allowed to do things like add their own extra template parameters (beyond those required by the standard), which, of course, your code wouldn't know about—one of the primary reasons for the rule that programmers aren't allowed to write their own declarations for things in namespace std."

My question:

I don't understand the part marked in bolds.

Thanks,


The part in bolds just says you can't forward declare ostream like this:

class ostream;
  • because ostream now is a typedef, and the details of declaration may or may not vary on different implementations.
  • because programmers are not allowed to declare anything in namespace std (though it will work on the majority of compilers).

If you want a forward declaration of ostream, include <iosfwd> instead. (Or look inside what it looks like for your implementation).


You can, if you are OK with the fact, that it will only work for a specific version of a specific compiler. It will be ugly, but you can do it (you can pretty much copy the content of the header into your code, and it will still work).

The reason why you shouldn't is exactly why it is in the header. You want to use some external interface and don't want to care about the compiler internals. The compiler guarantees you the external interface. As for the implementation, that's the compilers choice.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜