AM Z
AM Z

Reputation: 431

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")

Upvotes: 3

Views: 1907

Answers (2)

jfMR
jfMR

Reputation: 24738

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().

Upvotes: 2

Buddy
Buddy

Reputation: 11028

That’s called “template argument deduction” where it can figure it out based on what you’re passing in.

https://en.cppreference.com/w/cpp/language/template_argument_deduction

Upvotes: 0

Related Questions