Difference between revisions of "cpp/language/sizeof..."
From cppreference.com
(example: use variadic type instead of value) |
m (→Example: updated to make common_type_t be really useful; required C++20 now (although it can be converted back to C++11)) |
||
Line 19: | Line 19: | ||
{{example | {{example | ||
| code= | | code= | ||
− | |||
#include <array> | #include <array> | ||
+ | #include <iostream> | ||
#include <type_traits> | #include <type_traits> | ||
− | + | ||
template<typename... Ts> | template<typename... Ts> | ||
− | + | consteval auto make_array(Ts&&... ts) | |
− | + | ||
{ | { | ||
− | return { std::forward< | + | using CT = std::common_type_t<Ts...>; |
+ | return std::array<CT, sizeof...(Ts)>{ std::forward<CT>(ts)... }; | ||
} | } | ||
− | + | ||
int main() | int main() | ||
{ | { | ||
− | + | std::array<double, 4ul> arr = make_array(1, 2.71f, 3.14, '*'); | |
− | std::cout << | + | std::cout << "arr = { " << std::fixed; |
− | for (auto | + | for (auto s{arr.size()}; double elem : arr) |
− | std::cout << | + | std::cout << elem << (--s ? ", " : " "); |
+ | std::cout << "}\n"; | ||
} | } | ||
− | |output= | + | |output=arr = { 1.000000, 2.710000, 3.140000, 42.000000 } |
− | + | ||
− | 1 2 3 | + | |
}} | }} | ||
Revision as of 14:17, 17 August 2021
Queries the number of elements in a parameter pack.
Contents |
Syntax
sizeof...( parameter_pack )
|
(since C++11) | ||||||||
Returns a constant of type std::size_t.
Explanation
Returns the number of elements in a parameter pack.
Keywords
Example
Run this code
#include <array> #include <iostream> #include <type_traits> template<typename... Ts> consteval auto make_array(Ts&&... ts) { using CT = std::common_type_t<Ts...>; return std::array<CT, sizeof...(Ts)>{ std::forward<CT>(ts)... }; } int main() { std::array<double, 4ul> arr = make_array(1, 2.71f, 3.14, '*'); std::cout << "arr = { " << std::fixed; for (auto s{arr.size()}; double elem : arr) std::cout << elem << (--s ? ", " : " "); std::cout << "}\n"; }
Output:
arr = { 1.000000, 2.710000, 3.140000, 42.000000 }