Lets say I have the following scenario where I am printing templates of type std::size_t
.
假设我有以下场景,其中打印类型为std::SIZE_t的模板。
template<std::size_t st>
void print_sizes(){
std::cout << st << std::endl;
}
template<std::size_t st, std::size_t M, std::size_t... Rest>
void print_sizes(){
std::cout << st << std::endl;
}
int main(){
print_sizes<10, 12, 3>();
}
The above is entirely valid. However, I was wondering if there was a way to store the 10,12,3
variadic template like the following:
上述情况完全成立。然而,我想知道是否有一种方法来存储10,12,3可变模板,如下所示:
template<std::size_t st>
void print_sizes(){
std::cout << st << std::endl;
}
template<std::size_t st, std::size_t M, std::size_t... Rest>
void print_sizes(){
std::cout << st << std::endl;
print_sizes<M, Rest...>();
}
using example = 10, 12, 3;
int main(){
print_sizes<example>();
}
Obviously, that doesn't work and throws an error. Is there a way to do something like this though?
显然,这是不起作用的,并且会抛出错误。不过,有没有办法做到这一点呢?
更多回答
This is trivial. Wrap them into a type: template<std::size_t...> class wrapper {}; using example = wrapper<10, 12, 3>;
.
这是微不足道的。使用example = wrapper<10,12,3>;将它们包装到类型:template class wrapper {};中。
优秀答案推荐
You can't easily store the 10, 12, 3
parameter pack itself, but you can store a template instantiated over those parameters:
您不能轻松地存储10、12、3参数包本身,但您可以存储在这些参数上实例化的模板:
#include <iostream>
template<std::size_t st>
void print_sizes(){std::cout<<st<<std::endl;}
template<std::size_t st, std::size_t M, std::size_t... Rest>
void print_sizes(){
std::cout<<st<<std::endl;
print_sizes<M, Rest...>();
}
int main(){
auto f = print_sizes<10, 12, 3>; // save instantiated template
f(); // invoke it.
return 0;
}
Note that if you can use C++17 or newer, you probably want to use a fold expression instead of the variadic template.
请注意,如果您可以使用C++17或更高版本,您可能希望使用折叠表达式,而不是可变模板。
Since you seem to want a compile-time list of things of one type, you might prefer an initializer list:
由于您似乎想要一种类型的东西的编译时列表,您可能更喜欢初始化列表:
#include <iostream>
#include <initializer_list>
void print_sizes(std::initializer_list<std::size_t> numbers) {
for (auto num : numbers)
std::cout << num << "\n";
}
int main() {
print_sizes({10, 12, 3});
}
I think std::integer_sequence
(since C++14) and fold expression (since C++17) might be what you are looking for:
我认为std::INTEGER_SEQUENCE(从C++14开始)和Fold Expression(从C++17开始)可能就是您要寻找的:
Coliru
科里鲁
#include <iostream>
template <typename T, T... ints>
void print_sequence(std::integer_sequence<T, ints...> seq) {
((std::cout << ints << std::endl), ...);
}
constexpr auto seq = std::integer_sequence<size_t, 10, 12, 3>{};
int main() { print_sequence(seq); }
更多回答
These are good solutions, but the question is tagged C++11, so the answer should at least contain an alternative that works in C++11 as well.
这些都是很好的解决方案,但问题被标记为C++11,所以答案至少应该包含一个也适用于C++11的替代方案。
我是一名优秀的程序员,十分优秀!