2 つの古典的な可能性があります。
まず、2 つのグローバル関数オーバーロードを使用します。1 つは 用ComponentDc
、もう 1 つは 用ですComponentIc
。
void globalExec(ComponentDc) { std::cout << "Hello"; }
void globalExec(ComponentIc) { std::cout << "World"; }
void Device<Component>::exec() { globalExec(Component); }
2 番目に、 traits-class を使用します。フィールドを持たず、異なる typedef を持ち、メソッドとして静的関数のみを持つ純粋なテンプレート クラスです。このクラスには、さまざまな可能な引数の型に対する独自の特殊化があります。
template<Component> class DeviceTraits {};
template<> class DeviceTraits<ComponentDc> {
static std::string getMessage() { return "Hello"; }
};
template<> class DeviceTraits<ComponentIc> {
static std::string getMessage() { return "World"; }
};
void Device<Component>::exec() {
std::cout << DeviceTraits<Component>::getMessage();
}
特性クラスを使用する利点は、グローバル名前空間をいくつかの関数で台無しにする必要がないことです。
クラス自体の部分的な特殊化についてDevice
- 常に可能であるとは限らず、テンプレート引数固有のコードを traits クラスに移動する方が便利であると考えられます。
これは、STL で使用される古典的なアプローチです。あるいは、boost::enable_if
またはstd::enable_if
(最新のコンパイラの場合) を使用できます。