2

この質問をしてテンプレートについてたくさん読んだ後、クラステンプレートの次の設定が理にかなっているのかどうか疑問に思います。

、などのResourceManagerいくつかの特定のリソースのみをロードするというクラステンプレートがあります。明らかに、ResourceManager.hでクラステンプレートを定義します。ただし、明示的なインスタンス化はわずかしかないため、次のようなことを行うのが適切でしょうか...ResourceManager<sf::Image>ResourceManager<sf::Music>

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

// Define methods in ResourceManager, including explicit specializations

要するに、私はテンプレートクラスとそのメソッドの宣言と定義を処理するための最もクリーンな方法を見つけようとしています。その一部は明示的な特殊化である可能性があります。これは特殊なケースであり、使用される明示的なインスタンス化はごくわずかであることがわかっています。

4

2 に答える 2

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>;   
于 2010-08-20T20:47:02.610 に答える
-2

タイプに応じて関数の異なる実装が必要な場合は、テンプレートの代わりに継承を使用することをお勧めします。

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

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

class MusicManager : public ResourceManager {
    // Implement virtual functions.
}
于 2010-08-20T19:55:02.667 に答える