转发声明一个标准容器?
是否可以在头文件中转发声明标准容器? 例如,采用以下代码:
#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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在
std
命名空间中声明vector
是未定义行为。 因此,您的代码可能有效,但也可能无效,并且编译器没有义务告诉您您的尝试何时无效。 这是一场赌博,而且我不知道避免包含标准 C++ 头文件是否值得。请参阅以下 comp.std.c++.moderated 讨论:
转发声明 std::vector。 可行,但它符合法律和标准吗?
Declaring
vector
in thestd
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?
我不这么认为,因为编译器无法知道为
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:and new it in the constructor, since the compiler knows the size of a pointer.
除了其他人所说的之外,您可能会发现了解有一种前向声明 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.