Talk #3188 » bonus_array_deduction.cpp
1 |
/*
|
---|---|
2 |
* Created: 26-01-2016
|
3 |
* Modified: Wed 27 Jan 2016 17:59:23 CET
|
4 |
* Author: Jonas R. Glesaaen (jonas@glesaaen.com)
|
5 |
*/
|
6 |
|
7 |
#include<iostream>
|
8 |
#include<boost/type_index.hpp>
|
9 |
|
10 |
using boost::typeindex::type_id_with_cvr; |
11 |
|
12 |
//A function that demonstrates that the array size of a C-array
|
13 |
//is encoded into the type, and that this is accessible information
|
14 |
template <typename T, std::size_t N> |
15 |
constexpr std::size_t array_size(T (&)[N]) noexcept |
16 |
{
|
17 |
return N; |
18 |
}
|
19 |
|
20 |
//This function demonstrates some caveats when template deducing
|
21 |
//C-arrays. Only array references retain information about array size
|
22 |
//(does not compile for a call-by-value)
|
23 |
template <typename T> |
24 |
void print_arr(const T& arr) |
25 |
{
|
26 |
std::cout << "[" << array_size(arr) << "] "; |
27 |
for (auto i : arr) |
28 |
std::cout << i << ", "; |
29 |
|
30 |
std::cout << "\n"; |
31 |
|
32 |
//Uncomment to print out the deduced types of T and arr
|
33 |
//std::cout << "T: "
|
34 |
//<< type_id_with_cvr<T>().pretty_name() << ",\t"
|
35 |
//<< "x: "
|
36 |
//<< type_id_with_cvr<decltype(arr)>().pretty_name() << "\n";
|
37 |
}
|
38 |
|
39 |
int main(int, char**) |
40 |
{
|
41 |
int arr[] = {3, 1, 4, 1, 5, 9}; |
42 |
print_arr(arr); |
43 |
}
|