user438431
user438431

Reputation: 347

benefit of using template vs function and how to deduce type in template

I've read quite a few posts on deducing variable type, both using auto and without. I think I am down to two questions.

Lets take a simple range function as an example. I can make it a template and call it:

template <class T, T min, T max> bool inRange(T value) {
   return min <= value && value <= max;
}

bool bbb = inRange<int, 5, 10>(7);

or I can do:

template <class T> bool inRange(T min, T max, T value) {
    return min <= value && value <= max;
}

bool bbb = inRange(5, 10, 7);

Questions:

  1. Is there a way (short of creating multiple templates 1 each for short, int, long, double, etc) that the type can be deduced such that the template can be called with inRange<min, max>(value)

  2. Is there any advantage of inRange<min, max>(value) as to inRange(min, max, value)

Upvotes: 4

Views: 152

Answers (1)

n. m. could be an AI
n. m. could be an AI

Reputation: 119847

  1. Not at the moment. There is a proposal to add this to a future version of C++: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4469.html
  2. The first method inRange<T, min, max>(value) is rather awkward since we don't have the aforementioned proposal implemented yet and can't write inRange<min, max>(value). If min and max are not known at compile time, the second method inRange(min, max, value) is your only option anyway. An inline function of the second kind should be just as efficient as the first kind so there is rarely any advantage.

Upvotes: 1

Related Questions