转发声明一个标准容器?

发布于 2024-07-08 13:21:44 字数 359 浏览 6 评论 0原文

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

#include <vector>

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

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

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

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

这可以完成吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

孤独患者 2024-07-15 13:21:44

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

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

转发声明 std::vector。 可行,但它符合法律和标准吗?

Declaring vector in the std namespace 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.

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

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

长发绾君心 2024-07-15 13:21:44

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

std::vector<int> *container_;

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

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:

std::vector<int> *container_;

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

·深蓝 2024-07-15 13:21:44

除了其他人所说的之外,您可能会发现了解有一种前向声明 iostream 和一些相关模板的认可方法很有用:标头 。 如果标准有更多这样的标头将会很有用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文