mercredi 19 juillet 2017

How to handle casting in Heterogenous container

I am trying to implement Heterogenous container, using pointers to non-template base class. While the derived class is a template.

Note: Derived class types are known at compile time. Note: the container size is fixed.

First attempt: is using a helper array to hold integer representation of the correct type. Its size equal to the container size. Yet I ended up with many if statements.

my problem is slightly similar to this thread yet I don't know to how to use std::type_index.

I am trying to avoid solving this using Boost::variant and run-time polymorphism.

My question: is there better way to handle casting from the base class to the derived class ?

class Plant
{ public: std::string sound = "I am jst a plant";};

template <typename T>
class Fruit : public Plant
{public: std::string sound = "I am jst a Fruit!";};

// list of types known at compile time.
struct Apple{ };           // types = 0
struct Orange{ };          // types = 1
struct Banana{ };          // types = 2

template <>
class Fruit<Apple> : public Plant
{public: std::string sound = "I am Apple";};

template <>
class Fruit<Orange> : public Plant
{public: std::string sound = "I am Orange";};

template <>
class Fruit<Banana> : public Plant
{public: std::string sound = "I am Banana";};


template <typename T>
void MakeSound(T fruit)
{
    std::cout << fruit->sound << std::endl;
}

int main() {

    Plant* Basket[5] = {nullptr};
    int types[5] = {0};

    Basket[0] = new Fruit<Apple>;
    types[0] = 0;

    Basket[1] = new Fruit<Orange>;
    types[1] = 1;

    Basket[2] = new Fruit<Orange>;
    types[2] = 1;

    Basket[3] = new Fruit<Apple>;
    types[3] = 0;

    Basket[4] = new Fruit<Apple>;
    types[4] = 0;


    for (int i = 0; i < 5; ++i)
    {
        if (types[i] == 0)
        {
            MakeSound(static_cast<Fruit<Apple> *>(Basket[i]));
        }
        else if (types[i] == 1)
        {
            MakeSound(static_cast<Fruit<Orange> *>(Basket[i]));
        }
        else
        {
            MakeSound(static_cast<Fruit<Banana> *>(Basket[i]));
        }

    }
}

Aucun commentaire:

Enregistrer un commentaire