2010-08-20 58 views
2

在詢問this question並閱讀了很多模板之後,我想知道下面的類模板設置是否有意義。建立具有實例化類模板的類模板的方法

我有一個名爲ResourceManager的類模板,它只會加載一些特定的資源,如ResourceManager<sf::Image>,ResourceManager<sf::Music>等。顯然,我在ResourceManager.h中定義了類模板。然而,由於只有少數明確的實例,這將是適當的做這樣的事情......

// ResourceManager.cpp 
template class ResourceManager<sf::Image>; 
template class ResourceManager<sf::Music>; 
... 

// Define methods in ResourceManager, including explicit specializations 

總之,我試圖找出處理聲明和定義模板類的清潔方式其方法,其中一些可能是明確的專業化。這是一個特例,我知道只會使用一些明確的實例。

回答

3

是的。
這完全合法。

你可能想要隱藏一個事實,即它是在一個typedef後面模板化的(就像std :: basic_string那樣),然後在標題中放一個註釋,不要顯式地使用模板。

未需要什麼ResourceManager.h

template<typename T> 
class ResourceManager 
{ 
    T& getType(); 
}; 

// Do not use ResourceManager<T> directly. 
// Use one of the following types explicitly 
typedef ResourceManager<sf::Image> ImageResourceManager; 
typedef ResourceManager<sf::Music> MusicResourceManager; 

ResourceManager.cpp

#include "ResourceManager.h" 

// Code for resource Manager 
template<typename T> 
T& ResourceManager::getType() 
{ 
    T newValue; 
    return newValue; 
} 

// Make sure only explicit instanciations are valid. 
template class ResourceManager<sf::Image>;  
template class ResourceManager<sf::Music>; 
+0

謝謝!很有幫助。 – rhubarb 2010-08-20 21:18:45

-2

如果你需要函數的不同實現,取決於類型,我建議使用繼承而不是模板。

class ResourceManager { 
    // Virtual and non-virtual functions. 
} 

class ImageManager : public ResourceManager { 
    // Implement virtual functions. 
} 

class MusicManager : public ResourceManager { 
    // Implement virtual functions. 
} 
+0

沒有。重點是將類模板函數的定義放在頭文件中沒有#include的.cpp文件中(通常是在頭文件中定義模板函數)。除非明確指定類模板的特化,否則這不起作用。事實上,只有一個功能實際上需要專門化。 – rhubarb 2010-08-20 20:10:21