6

私が定数値を持っているとしましょう(おそらくいくつかの列挙型)。私は多くのクラスA、B、Dなどを持っているとしましょう.

私はこのようなものを持つことができますか?

C<1> anInstanceOfA; //This will be of type A
C<2> anInstanceOfB; //This will be of type B
C<3> anInstanceOfD; //This will be of type D

では、コンパイル時に定数に基づいてクラスを選択することは可能ですか?

一般的な問題は、インデックスが列挙型であるテーブルに基づいてファンクターを選択しようとしていることです。できればポリモーフィズムは避けたいです。

編集:このプロジェクトでは、C++ 11 を使用できません。とにかく、そのコンテキストで回答した人に感謝します。とにかく知るのは非常に興味深いです。
編集 2:一般に、2 つ以上のターゲット クラスを持つことができます。質問を編集しました。

4

3 に答える 3

11

これはこれを行う唯一の方法ではありませんが、目的に応じて受け入れられることを願っています:

struct A { };
struct B { };

template <int N>
struct choices;

template <>
struct choices<1> { typedef A type; };

template <>
struct choices<2> { typedef B type; };

template <int N>
using C = typename choices<N>::type;

更新: C++11 機能なしで同じことを行うには、上記の対応する型エイリアスと等しいメンバー型Cを持つクラスを作成する必要があります。typedef

template <int N>
struct C
{
    typedef typename choices<N>::type type;
};

// ...
C<1>::type anInstanceOfA;
C<2>::type anInstanceOfB
于 2013-07-30T14:55:12.003 に答える
9

LSP とプレーンな C++98 を使用する:

template <int N> class C;
template <> class C<1> : public A {};
template <> class C<2> : public B {};
template <> class C<3> : public D {};

C<1> anInstanceOfA;

C++ の public 継承は IS-A 規則を満たすため、 IS-Aオブジェクトと IS_ANオブジェクトanInstanceOfAの両方。C<1>A

于 2013-07-30T15:20:55.250 に答える
4

これはかなり単純なメタ関数です。

template <int N>
struct C {
  typedef typename std::conditional<N == 1,A,B>::type type;
};

これを として使用しC<1>::type foo;ます。

コンパイラが C++11 テンプレート エイリアスをサポートしている場合は、次のように簡略化できます。

template <int N>
using C = typename std::conditional<N == 1,A,B>::type;

好みのC<1> foo;構文があります。

純粋な C++03 では、次のように実装std::conditionalします。

template <bool, typename A, typename>
struct conditional {
  typedef A type;
};

template <typename A, typename B>
struct conditional<false, A, B> {
  typedef B type;
};
于 2013-07-30T14:54:00.460 に答える