0

I have a library where template classes/functions often access explicit members of the input type, like this:

template <
typename InputType>
bool IsSomethingTrue(
  InputType arg1) {

  typename InputType::SubType1::SubType2 &a;

  //Do something

}

Here, SubType1 and SubType2 are themselves generic types that were used to instantiate InputType. Is there a way to quickly find all the types in the library that are valid to pass in for InputType (likewise for SubType1 and SubType2)? So far I have just been searching the entire code base for classes containing the appropriate members, but the template input names are reused in a lot of places so it is very cumbersome.

From a coding perspective, what is the point of using a template like this when there is only a limited set of valid input types that are probably already defined? Why not just overload this function with explicit types rather than making them generic?

2
  • 1
    Why did you need to do this? Mar 13, 2013 at 20:00
  • I am trying to port selected functions in the library to python; I would use the library directly but I work on a closed IS where getting the necessary third party libraries set up would be difficult.
    – Joe Mango
    Mar 13, 2013 at 20:09

2 Answers 2

2

From a coding perspective, what is the point of using a template like this when there is only a limited set of valid input types that are probably already defined? Why not just overload this function with explicit types rather than making them generic?

First of all, because those overload would have the exact same body, or very similar ones. If the body of the function is long enough, having more versions of it is a problem for maintenance. When you need to change the algorithm, you now have to do it N times and hope you won't make mistakes. Most of the times, redundancy is bad.

Moreover, even though now there could be just a few such types which satisfy the syntactic requirements of your function, there may be more in future. Having a function template allows you to let your algorithm work with new types without the need to write a new overload every time one new such type is introduced.

0

The advantage of using generic types is not on the template end: if you're willing to explicitly name them and edit the template code every time, it's the same.

What happens, however, when you introduce a subclass or variant of a type accepted by the template? No modification needed on the other end.

In other words, when you say that all types are known beforehand, you are excluding code modifications and extensions, which is half the point of using templates.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.