C ++ 11可变数量的参数,相同的特定类型 [英] C++11 variable number of arguments, same specific type
本文介绍了C ++ 11可变数量的参数,相同的特定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题很简单,我将如何实现一个带有可变数量参数(类似于可变参数模板)的函数,但是所有参数都具有相同类型(例如int)。
Question is simple, how would I implement a function taking a variable number of arguments (alike the variadic template), however where all arguments have the same type, say int.
我在想类似的东西;
void func(int... Arguments)
或者不会对类型工作使用递归静态断言吗?
Alternatively wont a recursive static assert on the types work?
推荐答案
一种可行的解决方案是使参数类型成为可以由括号初始化程序列表(例如 std :: initializer_list< int>
或 std :: vector< int>
。 例如:
A possible solution is to make the parameter type a container that can be initialized by a brace initializer list, such as std::initializer_list<int>
or std::vector<int>
. For example:
#include <iostream>
#include <initializer_list>
void func(std::initializer_list<int> a_args)
{
for (auto i: a_args) std::cout << i << '\n';
}
int main()
{
func({4, 7});
func({4, 7, 12, 14});
}
这篇关于C ++ 11可变数量的参数,相同的特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文