<分区>
我认为这是 C++ 的精神——不为不为所欲为 想要(你明确支付你需要的东西):
// a.h
#include <iosfwd>
template< class T >
class QVector;
struct A
{
void process( QVector<int> );
void print( std::ostream& );
};
// some.cpp
#include "a.h"
#include <iostream> // I need only A::print() in this module, not full interface
...
A().print( std::cout );
...
这就是为什么我认为禁止开发人员工作是不公平的 这种方式与 STL ( Will C++11 STL have forward declaration's files? )。
但我也看到了一件坏事:模块 A 的依赖性
将在外部上下文中传播(#include
指令的重复)并且它可能导致硬重构
界面何时更改(例如,将 QVector 替换为 QList - 现在您需要将所有出现的 <QVector>
替换为 <QList>
)。
解决这个问题是:
#include <iostream>
#include <QVector>
struct A
{
void process( QVector<int> );
void print( std::ostream& );
};
我们是否应该将其称为成语“接口(interface)的基本类型” - 模块 接口(interface)的类型应该像基础类型(总是 定义和可用)?也有道理,但还是不清楚 哪种方法更好(例如 Qt 混合了这两种方法)。
我个人的决定 - 始终提供两种方式以获得更好的模块化(当我们有足够的依赖性时):
// a_decl.h
#include <iosfwd>
template< class T >
class QVector;
struct A
{
void process( QVector<int> );
void print( std::ostream& );
};
// a.h
// Include this file if you want to use most interface methods
// and don't want to write a lot of `#include`
#include <iostream>
#include <QVector>
#include "a_decl.h"
并让开发者选择要包含的内容。
您对这些方法有何看法?哪种方式更适合您,为什么?对于所有案例,我们是否都有一个明显的赢家,还是始终取决于具体情况?
来 self 与语言创造者的通信(我没有收到最终答复)
更新:
随着 boost 1.48.0 的推出,Container 库允许定义未定义用户类型的容器 ( read more )。