How to make a Template Function in C

68 views Asked by At

I'm writing a code for task which contain only two data structure(6 queues and 4 collections). But the problem is that I do not know exactly which data structures I will need until the moment of compilation because i'm configuring information in file. I ask a question to solve one of several problem and there was a good solution for me. I use void* and enum for type. And then use switch-case for handling all cases; But then i have a NEW PROBLEM: I don't wanna create six different realisations for each of collection type.

Config file look like:

BinomialHeap
HashSet
23:17:57 03/09/24
23:17:57 03/09/24
36 min_time_for_1_request
43 max_time_for_1_request 
52 number_of_department
48 34 36 19 30 19 48 42 49 46 39 18 13 36 49 20 17 23 10 18 48 18 30 11 13 24 42 33 24 21 40 23 45 25 32 24 34 29 17 34 24 47 43 29 34 43 39 43 17 41 12 14

1.571111 - overload_coeff

And then created queue and enumerates for data types:

typedef enum queue_type {
    BINARY_Q,
    BINOMIAL_Q,
    LEFTIST_Q,
    SKEW_Q,
    FIBONACCI_Q,
    TREAP
} queue_type;

typedef enum collection_type
{
    BST_T,
    VECTOR_T,
    HT_T,
    UNKNOWN_T,
} collection_type;

void QUEUE_FUNC(void *data, const queue_type type)
{
    switch(type)
    {
        case BINARY_Q:
            printf("BINARY_Q\n");
            break;
        case BINOMIAL_Q:
            printf("BINOMIAL_Q\n");
            break;
        case FIBONACCI_Q:
            printf("FIBONACCI_Q\n");
            break;
        case SKEW_Q:
            printf("SKEW_Q\n");
            break;
        case LEFTIST_Q:
            printf("LEFTIST_Q\n");
            break;
        case TREAP:
            printf("TREAP\n");
            break;
        default:
            printf("Unknown type\n");
            break;
    }
}

Main look like:

int main(int argc, char* argv[])
{
    generate_config("out.txt"); // CONFIGURE INFO FILE

    // READ AND PARSE FILE

    size_t q_size = 0;
    queue_type q_type = 0;
    void *queue_data = NULL;

    if (!strcmp(queue_str, "BinaryHeap")) { q_size = sizeof(VECTOR); q_type = BINARY_Q;}
    else if (!strcmp(queue_str, "BinomialHeap")) { q_size = sizeof(HT); q_type = BINOMIAL_Q;}
    else if (!strcmp(queue_str, "FibonacciHeap")) { q_size = sizeof(BST); q_type = FIBONACCI_Q;}
    else if (!strcmp(queue_str, "SkewHeap")) { q_size = sizeof(BST); q_type = SKEW_Q;}
    else if (!strcmp(queue_str, "LeftistHeap")) { q_size = sizeof(BST); q_type = LEFTIST_Q;}
    else if (!strcmp(queue_str, "Treap")) { q_size = sizeof(BST); q_type = TREAP;}


    if (q_size != 0 ) queue_data = malloc(q_size);
    
    QUEUE_FUNC(queue_data, q_type); 
}

And If i had a HashSet, i need to store a Queue in HashSet, but i actually don't know HOW. Thank you for reading.

0

There are 0 answers