Zadania

  1. any.h, any.c: stwórz bibliotekę, która definiuje typ any pozwalający na przechowanie wielu różnych typów:

    1. typedef struct any { /* zdefiniowane przez osobę studencką */ } any_t;, które zawiera ręcznie stworzoną vtable

    2. any_t any_from_int(int x); - funkcja tworząca wartość any z wartości liczbowej

    3. any_t any_from_str(char const* s); - funkcja tworząca wartość any z ciągu znaków

    4. any.length(any); - zwraca długość reprezentacji dziesiętnej dla liczby, długość łańcucha dla ciągu znaków

    5. any.free(any); - czyszczące zaalokowaną pamięć jeśli taka była potrzebna

    6. any.print(any); - wypisujące wartość na standardowe wyjście (wraz z znakiem nowej linii)

Przykład vtable

#include <stdio.h>
#include <math.h>

typedef struct shape {
    union
    {
        struct
        {
            float radius;
        };

        struct
        {
            float width, height;
        };
    };

// vtable:
    float (*area)(struct shape *this);
    void (*print)();
} shape;

float circle_area(struct shape *this)
{
    return M_PI * this->radius * this->radius;
}

shape circle(float r)
{
    struct shape s;
    s.radius = r;
    s.area = circle_area;
    return s;
}

float rect_area(struct shape *this)
{
    return this->width * this->height;
}

shape rectangle(float w, float h)
{
    struct shape s;
    s.width = w;
    s.height = h;
    s.area = rect_area;
    return s;
}

int main()
{
    shape s = rectangle(10, 20);
    printf("Area is: %f\n", s.area(&s));
    return 0;
}