[英]Variable amount of function arguments in C++
So, in C the standard way is stdarg.h. 因此,在C中,标准方式是stdarg.h。 But I'm looking to pull up something a bit like this:
但我希望提出类似以下的内容:
template<int A>
class MyClass {
public:
MyClass(...) {
// fill each value of array with an argument.
};
virtual ~MyClass() { };
private:
float array[A];
};
Obviously, the idea is not to have different constructions for every possible amount of arguments. 显然,这种想法是,对于每种可能的论点,都不应有不同的结构。 Any suggestions, standard ways, whatsoever?
有什么建议,标准方法吗?
Thanks, 谢谢,
Julian. 朱利安。
In C++11 you can use an std::initializer_list constructor for this kind of scenario. 在C ++ 11中,可以将std :: initializer_list构造函数用于这种情况。 That allows for this type of initialization:
这允许这种类型的初始化:
MyClass<5> x{1,2,3,4,5};
although you have to define what happens when the dimensions do not match. 尽管您必须定义尺寸不匹配时会发生什么。 But for these kinds of statically sized arrays, it is worth looking at std::array .
但是对于这类静态大小的数组,值得研究std :: array 。 These have a well defined behaviour when the dimensions of the initializer don't match their own.
当初始值设定项的尺寸与自己的尺寸不匹配时,它们具有明确定义的行为。
you need to use initializer_list
您需要使用
initializer_list
explicit MyClass(std::initializer_list<T> list_args){
// fill each value of array with an argument.
};
If you don't have access to C++11 initializer_lists you can just pass a vector. 如果您无权访问C ++ 11 initializer_lists,则可以传递一个向量。
MyClass(const std::vector& values) {
//copy values into array
};
MyClass someClass( std::vector<int>(10,4) ); //adds 10x 4 to the vector
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.