0

Given the snippet of code below:

template<int n, double m>
void function(int x=n){
 double y=m;
 int array[n];
 ….
}

void main () {
 function<1+2,2>(8);
}

when the function is compiled is x going to be 3 or 8 (as n is just the default parameter)?

wayta
  • 35
  • 7

2 Answers2

1

In your example n is 3 and x is 8. The actual parameter value takes precedence over the default one.

dlask
  • 8,776
  • 1
  • 26
  • 30
1

what's the benefit of that code!!.

The template non-type parameter must be a structural type (can't be double). See https://en.cppreference.com/w/cpp/language/template_parameters#Non-type_template_parameter

Hence If the double changed to be int, the vars would be x=8, n=3 and m=2.

Another thing change void main() to int main(). See What should main() return in C and C++?

asmmo
  • 6,922
  • 1
  • 11
  • 25
  • 1
    it was shown in one of the slides in my course. it's for pure educational purpose, no real utility. Thank you! – wayta Mar 28 '20 at 16:58