Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How that works ! (template<std::size_t Size>)

#include <iostream>
#include <array>

#define print(x) std::cout << x
#define println(x) std::cout << x << std::endl

template<std::size_t Size>
void Print(std::array<int, Size>& arr) {
    for (int i = 0; i < Size; i++) {
        println(arr[i]);
    }
}

int main() {
    std::array<int, 5> arr = {1, 2, 3, 4, 5};
    Print(arr);
}

How does the size got passed to the function template without defining it like Print<5>(arr) ? (at line 7 "the actual template", at line 16 "calling the function")

like image 385
AM Z Avatar asked Nov 23 '25 10:11

AM Z


1 Answers

How does the size got passed to the function template without defining it like Print<5>(arr) ?

It is thanks to template argument deduction. The size is deduced from the call Print(arr). Print() is a function template with a non-type template parameter (i.e., Size) of type std::size_t:

template<std::size_t Size>
void Print(std::array<int, Size>&);

That is, the template parameter Size is deduced to a value of type std::size_t, which corresponds to the second template argument of the std::array passed as a function argument when calling Print().

like image 151
ネロク・ゴ Avatar answered Nov 24 '25 23:11

ネロク・ゴ