Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why pass a value to a template instead of supplying it in a function call?

Tags:

c++

templates

As I'm going along learning C++, there is a concept that I am not able to fully grasp and comprehend the reasoning behind the mechanics. And that topic is: Function templates and the passing of arguments at compile time, rather than run time.

What I want to know is, the reasoning behind the design in passing the values of --lets say for example-- an int value, at compile time. I'm thinking it was possible that the developers of C++ could've allowed the passing of value at run-time, but what I want to know is this -- The reasoning of choosing to pass the value of, lets say an int, during compile time. Of course I'm talking about function templates like this one :

#include <iostream>
using namespace std;

template <class T, int N>
T fixed_multiply (T val)
{
  return val * N;
}

int main() {
  std::cout << fixed_multiply<int,2>(10) << '\n';
  std::cout << fixed_multiply<int,3>(10) << '\n';
}

To my knowledge, the int value assigned in the calling of the template function (in this case the <2> and <3>) are calculated at compile time. What is the reasoning behind the design of these mechanics? I understand it is to create a different instance of each function, one that multiplies by 2, and one that multiplies by 3, respectively. Because of that, it cannot be passed a variable, it must be passed a constant.

But why is this necessary? I feel that the designers could've allowed run time execution, so that the values passed to it could be variables, but obviously the designers thought it would be better this way.

Thanks.

like image 759
savageWays Avatar asked Oct 01 '22 04:10

savageWays


1 Answers

Sometimes more optimizations are possible when one of the operands is a known constant.

For example, on the x86 architecture, a multiply by (constant) 3 can be implemented with the LEA instruction which runs much faster than IMUL. Division of an unsigned integer variable by a constant power of two can be replaced by right bit-shift, (and modulo by bitwise-AND).

like image 113
Ben Voigt Avatar answered Oct 13 '22 12:10

Ben Voigt