user606547
user606547

Reputation:

Template or function overload for generic argument

I have a function which takes three arguments

void replace(const string, const string, string*) ;

My problem is the second argument which I'd like to rewrite so it can be either a string or a Path object (from the Boost Filesystem library, but really any object that can be treated as a string should do) so I don't have to convert paths to strings all over the place.

I know I can overload the function and make two implementations, that's what I do now so I have two implementations of the same function:

void replace(const string, const string, string*) ;
void replace(const string, const path, string*) ;

But that doesn't seem very elegant, even if the second one just converts the path to a string and calls the first (so not much code duplication). I've tried using templates instead, like this:

template <class T>
void replace(const string, const T, string*) ;

But the implementation of the function requires that it is a string, so if it is given a path it needs to be converted to a string within the function, which I'm not sure how to do or if it's even a good thing to do.

To further complicate matters, in the future I might want to expand the function so it can also take a set of strings or a set of paths instead of just one string/path as the second argument.

What is the best way to handle all this? Is there no better way than having more than one implementation of the same function?

Upvotes: 1

Views: 803

Answers (2)

Alok Save
Alok Save

Reputation: 206546

Overloaded functions is the best approach for your use case.

I usually go by the following rules:

  • If you want to perform same actions on different data types then prefer templates.

  • If you want to perform different actions on different data types then prefer function overloading.

Your use case falls in the second category.

Upvotes: 6

Brendan Long
Brendan Long

Reputation: 54242

Why not just make a function like:

void replace(const string s, const path p, string* ss) {
    replace(s, convert_to_string(path), ss);
}

Let the optimizer decide how it should handle that. What's not elegant about it? Your template method will do the same thing, it'll just be more complicated.

Upvotes: 1

Related Questions