Why does the template value parameter have to be constant if code generation is performed at runtime?

template<int a> void foo () { cout << a << endl; } int main() { int b = 10; foo<b>(); return 0; } 
  • one
    dratuti, patterns unfold at compilation stage - goldstar_labs
  • "code generation is done at runtime" - where did you get this from? All code is "created" at compile time. - AnT

1 answer 1

In general, it is not clear what you want to write.
If you need a template printing function, then you do it wrong, you need this:

 template<typename T> void foo (const T& var) { std::cout << var << std::endl; } int main() { int b = 10; foo(b); return 0; } 

When compiling this code, the template function foo will be expanded for type int.
On the syntax of the templates a lot of information on the Internet.
http://cppstudio.com/post/5188/
https://ru.wikipedia.org/wiki/%D0%A8%D0%B0%D0%B1%D0%BB%D0%BE%D0%BD%D1%8B_C%2B%2B

  • I do not need the template print function) I wondered why only constant types can be used in the template value parameter - Vitaly
  • those. if const int b = 10 everything works - Vitaly
  • A template argument can be a type or a constant object. Why is that? .. Imagine an automated hat production process. All mechanisms are already programmed to act as they are (identical to the notion “code is executed at compile time”). You just need to enter the size of the hat at run time If the size during production will change in an unpredictable way, and not by our team “make hats of a different type”, then you know what you get ... But in the textbooks you will find detailed information, just need to take and read - AR Hovsepyan
  • @ARHovsepyan, thank you - Vitaly