【发布时间】:2011-10-25 20:51:18
【问题描述】:
我经常使用前向声明;它们有助于避免许多#includes,缩短编译时间等等。但是如果我想在标准库中前向声明一个类呢?
// Prototype of my function - i don't want to include <vector> to declare it!
int DoStuff(const std::vector<int>& thingies);
我听说禁止/不可能转发声明 std::vector。现在this answer to an unrelated question 建议这样重写我的代码:
stuff.h
class VectorOfNumbers; // this class acts like std::vector<int>
int DoStuff(const VectorOfNumbers& thingies);
stuff.cpp
// Implementation, in some other file
#include <vector>
class VectorOfNumbers: public std::vector<int>
{
// Define the constructors - annoying in C++03, easy in C++11
};
int DoStuff(const VectorOfNumbers& thingies)
{
...
}
现在,如果我在整个项目的所有上下文中都使用VectorOfNumbers 而不是std::vector<int>,一切都会好起来的,我不再需要在我的头文件中使用#include <vector>!
这种技术有很大的缺点吗?能够转发声明vector 的收益是否超过了它们?
【问题讨论】:
标签: c++ c++11 forward-declaration c++-standard-library