Noone AtAll
Noone AtAll

Reputation: 385

Is there a way to combine multiple almost-same functions?

Hardware stuff,
Interrupts need void(*)() - static function

So if I want interrupt to call members of specific object T t, I have to create some T* t_star for static function void foo(){ t_star->whatever;}to refer to.
If I want several interrupts, I have to have several such pairs of function-global_pointer

T* t_star_1;
void foo_1() {t_star_1->whatever;}
T* t_star_2;
void foo_2(){t_star_2->whatever;}
...

As you can see, this causes code bloat of pretty much same thing
Now, combining T* is obvious - T* Array[5]

How do I do the same for functions? They differ only in a single array index now... Is there a way to not write each and one of them?

Upvotes: 2

Views: 198

Answers (1)

JaMiT
JaMiT

Reputation: 16853

They [functions] differ only in a single array index now...

Sounds like what templates are designed to handle.

template <unsigned Index>
void foo()
{
    Array[Index]->whatever;
}

Your callbacks would then be foo<0>, foo<1>, etc. (It is strange that these callbacks take no parameters, though. In my experience, this sort of API often allows a void* parameter to pass data to the callback so that you do not have to resort to global variables.)

Here is another possibility, depending on how you planned to populate your array. This assumes you could initialize Array[i] to the return value of get_data(i). This has the benefit of not requiring global variables.

template <unsigned Index>
void foo()
{
    static T * data = get_data(Index);
    data->whatever;
}

Upvotes: 1

Related Questions