2011-11-06 33 views
1

我認爲這是C++的精神 - 你不支付你不 想(你明確地支付你所需要的):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指令重複)展開,它可以導致難以重構 時,界面會改變(例如使用的QList取代QVector - 現在您需要用<QList>替換所有出現的<QVector>)。這個問題

解決方案

#include <iostream> 
#include <QVector> 

struct A 
{ 
void process(QVector<int>); 

void print(std::ostream&); 
}; 

我們應該把這個成語「界面的基本類型」 - 接口的類型應該是這樣的基本面類型的模塊(總是 定義和可用)?這也是有道理的,但仍不清楚 什麼方式更好(例如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" 

,並讓開發者選擇中包括的內容。

你可以對這些方法說些什麼?什麼方法對你更好,爲什麼?對於所有情況,我們是否有明確的贏家?或者它總是取決於上下文嗎?

我與語言的創造者對應(我沒有收到最終的答案)

UPDATE:

隨着升壓1.48.0自帶容器庫,它允許定義不確定的用戶類型的容器(read more)。

+0

我很困惑。關於模塊? – Pubby

+0

是的,在C++中沒有這樣的關鍵字,但*模塊性*是所有面向對象語言的通用概念,至少 –

回答