This post就是我剛纔讀的。如何在C++中實現Singleton
他在C++中實現Singleton的方式讓我感到困惑。我得到了這幾個問題,而且這裏是他的代碼:
template<typename T>
class Singleton {
public:
static T& getInstance() { //Question 1
return instance;
}
private:
static T instance;
};
class DebugLog : public Singleton<DebugLog> { //Question 2
public:
void doNothing() {}
};
問題
我想我們應該把
static T& getInstance()
的定義類主體以外的,對不對?他試圖讓
class DebugLog
成爲一個單獨的類,但是當他繼承Singleton<DebugLog>
時,DebugLog
不存在了吧?如果對,那麼模板類Singleton
如何實例化一個不存在的類?
1 - 你不需要。 2 - [好奇地重複出現的模板模式](http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern)。 – birryree
@birryree,謝謝。 – Alcott