-2

私のプログラムはユーザーの入力を読み取り、簡単な「テーブル」を作成します。ユーザーは、最初に列のデータ型と行数を指定します。

ユーザーの入力:

create table
add attribute string Name
add attribute int    Age
rows                   3

今、ユーザーの入力から構造を準備する必要があります。私はこのようなものを持っています:

CTable
{
    unsigned   attributesCnt;
    string   * attributesNames;

    void    ** attributes;
};

したがって、ユーザーの入力から、プログラムは次の手順を実行します。

CTable myTable;

myTable.attributesCnt = 2; // string "Name", int "Age"

myTable.attributesNames = new string[2];
myTable.attributesNames[0] = "Name";
myTable.attributesNames[1] = "Age";

attributes = new void[2]; // 2 attributes
attributes[0] = (void*) new string[3]; // there will be 3 rows
attributes[1] = (void*) new int[3];

「attributes[0]」は文字列で、「attributes[1]」も int であることを覚えておく必要があります。

これは「正しい」方法ですか?

標準ライブラリのみを使用したい。

4

1 に答える 1

1

探しているのは、バリアントとも呼ばれるタグ付きユニオンです。通常のユニオンと同じように複数のデータ型を同じ場所に格納できますが、その型を示す別のデータ メンバーが追加されています。C++ 標準ライブラリにはバリアントは含まれていませんが、実装は簡単です。

バリアントを作成したら、以下のように例に適用できます。

myTable.attributesNames[0] = "Name";
myTable.attributesNames[1] = "Age";

// I recommend using std::vector here instead of using new/delete yourself
attributes = new Variant*[2]; // 2 attributes
attributes[0] = new Variant("player name");
attributes[1] = new Variant(player_age);

次の例は、バリアントの実装方法を示しています。

struct Variant
{
    enum Type
    {
        INT,
        STRINGPTR
    };

    Type    type_;
    union
    {
        int         int_;
        const char* stringptr_;
    }       data_;

    explicit Variant(int data) : type_(INT)
    {
        data_.int_ = data;
    }

    explicit Variant(const char *data) : type_(STRINGPTR)
    {
        data_.stringptr_ = data;
    }

    Type getType() const { return type_; }
    int getIntValue() const
    {
        if(type_ != INT)
            throw std::runtime_error("Variant is not an int");
        return data_.int_;
    }

    const char *getStringPtr() const
    {
        if(type_ != STRINGPTR)
            throw std::runtime_error("Variane is not a string");
        return data_.stringptr_;
    }
};

int main()
{
    Variant intval(1);
    Variant stringval("hello");

    std::cout << intval.getIntValue() << std::endl;
    std::cout << stringval.getStringPtr() << std::endl;
}
于 2013-05-27T09:51:20.107 に答える