C++ 转发声明一个标准容器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/307343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:29:36  来源:igfitidea点击:

Forward declare a standard container?

c++headerc++-standard-library

提问by Rob

Is it possible to forward declare an standard container in a header file? For example, take the following code:

是否可以在头文件中转发声明标准容器?例如,采用以下代码:

#include <vector>

class Foo
{
private:
    std::vector<int> container_;
    ...
};

I want to be able to do something like this:

我希望能够做这样的事情:

namespace std
{
    template <typename T> class vector;
}

class Foo
{
private:
    std::vector<int> container_;
    ...
};

Can this be done?

这能做到吗?

采纳答案by Rob Kennedy

Declaring vectorin the stdnamespace is undefined behavior. So, your code might work, but it also might not, and the compiler is under no obligation to tell you when your attempt won't work. That's a gamble, and I don't know that avoiding the inclusion of a standard C++ header is worth that.

vectorstd命名空间中声明是未定义的行为。因此,您的代码可能有效,但也可能无效,并且编译器没有义务在您的尝试无效时告诉您。这是一场赌博,我不知道避免包含标准 C++ 头文件是否值得。

See the following comp.std.c++.moderated discussion:

请参阅以下 comp.std.c++.moderated 讨论:

forward declaring std::vector. Works, but is it legal and standard compliant?

前向声明 std::vector。有效,但是否符合法律和标准?

回答by Evan Teran

I don't think so because the compiler would have no way of knowing how much space to allocate for the container_object. At best you could do:

我不这么认为,因为编译器无法知道要为container_对象分配多少空间。充其量你可以这样做:

std::vector<int> *container_;

and new it in the constructor, since the compiler knows the size of a pointer.

并在构造函数中新建它,因为编译器知道指针的大小。

回答by Sebastian Mach

Apart from what the others said, you may find it useful to know that there is a sanctioned way of forward-declaring iostreams and some related templates: The header <iosfwd>. It would be useful if the standard had more such headers.

除了其他人所说的之外,您可能会发现知道有一种预先声明 iostream 和一些相关模板的认可方式很有用: header <iosfwd>. 如果标准有更多这样的标题,那将会很有用。