Traz Daczkowski
Traz Daczkowski

Reputation: 15

C++ Have Function Accept types int and int[] using Templates

I have an existing code base with thousands of calls to foo(int bar[],int type) where in the function a number of structures are created where x[i].bar=bar[i] and x[i].type=type.
Now there's an edge case where I need to have different types for each x. So foo(int bar[], int type[]) leads to x[i].bar=bar[i] and x[i].type=type[i].

I currently have this implemented as an overload but that leads to a lot of copy pasted code. Is there a way to do this using templates?

Upvotes: 1

Views: 91

Answers (2)

anatolyg
anatolyg

Reputation: 28251

You can make a third function, which is a "generalization" of the two. It should receive parameters of both "flavors", with a way to specify which flavor you want.

void foo_internal(int bar[], int type[], int default_type)
{
    ...
    x[i].bar = bar[i];
    x[i].type = (type == nullptr) ? default_type : type[i];
    ...
}

Put all your long code in there, then call it from both your overloads:

void foo(int bar[], int type[])
{
    foo_internal(bar, type, 0);
}

void foo(int bar[], int type)
{
    foo_internal(bar, nullptr, type);
}

Upvotes: 1

user7451183
user7451183

Reputation:

Don't think the template could solve your problem, because a template function will be something like this

template<typename T>
void foo(int bar[],T type){
 ...
}

how do you manage to use type as int or int[] in generic way?

Instead you could refactor your code in order make foo(int bar[],int type) be used by foo(int bar[],int[] type), doing something like this

void foo(int bar[],int type)
{
  ...
}

void foo(int bar[],int[] type)
{
  ...
  foo(bar,type[i]);
  ...
}

in this way, you should avoid to duplicate the code.

Upvotes: 0

Related Questions