Forward-declaring library names

ⅰ亾dé卋堺 提交于 2019-12-13 02:57:14

问题


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,


回答1:


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).




回答2:


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.



来源:https://stackoverflow.com/questions/3222351/forward-declaring-library-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!