1

それで、この質問は以前に尋ねられましたが、タイトルにそれらのキーワードのいくつかを含む質問が欲しかった.

問題は単純です: クラスのインスタンスごとではなく、テンプレートのインスタンスごとに一意の数値識別子があるように、テンプレート化されたクラスを作成するにはどうすればよいでしょうか?

つまり、区別する方法は次のとおりです。

foo<int> f1;
foo<char> f2;
classID(f1) != classID(f2);

しかし、

foo<int> f3;
foo<int> f4;
classID(f3) == classID(f4);

関連:

C ++では、シングルトンを使用して各クラスが一意の整数IDを持つようにする方法は?

テンプレート化されたクラスのインスタンスへの一意の数値識別子の割り当て

4

2 に答える 2

2
template<class T>
class Base
{
public:
    static void classID(){}
private:
    T* t;
};

int main()
{
    Base<int> foo;
    Base<int> foo2;
    Base<char> foo3;

    /*
    unsigned int i  = reinterpret_cast<unsigned int>(Base<int>::classID);
    unsigned int ii = reinterpret_cast<unsigned int>(Base<char>::classID);
    unsigned int iii = reinterpret_cast<unsigned int>(Base<int>::classID);
    /*/
    unsigned int i  = reinterpret_cast<unsigned int>(foo.classID);
    unsigned int ii  = reinterpret_cast<unsigned int>(foo2.classID);
    unsigned int iii  = reinterpret_cast<unsigned int>(foo3.classID);
    //*/

    return ((i != ii) + (i <= ii) + (i >= ii)) == 2;
}

それが方法です!軽量で非常に簡単で、RTTI を使用していませんが、途方もなく安全でない reinterpret_cast を使用しています。

でも、多分私は何かが足りないのですか?

于 2010-02-01T07:48:24.160 に答える
0

これには静的関数を使用して、そのクラスを継承できると思います。

struct IdCounter { static int counter; };
int IdCounter::counter;

template<typename Derived>
struct Id : IdCounter {
  static int classId() {
    static int id = counter++;
    return id;
  }
};

struct One : Id<One> { };
struct Two : Id<Two> { };

int main() { assert(One::classId() != Two::classId()); }

もちろん、それは静的なコンパイル時定数ではありません-自動的に可能だとは思いません(これらの型を手動でいくつかの型リストに追加する必要がありますmpl::vector)。型が等しいかどうかを比較するだけで、これらすべてが必要ではないことに注意してください。is_sameコンパイル時定数を生成する(boostや他のライブラリにあり、書くのは簡単です)を使用するだけです

template<typename A, typename B>
struct is_same { static bool const value = false; };
template<typename A> 
struct is_same<A, A> { static bool const value = true; };

int main() { char not_true[!is_same<One, Two>::value ? 1 : -1]; }
于 2010-02-01T07:57:43.463 に答える