简体   繁体   English

C ++中可变数量的函数参数

[英]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.

相关问题 C ++可变数量的参数,格式为std :: cout - C++ variable amount of arguments with formatting for std::cout 带有不同参数的C ++ std :: function变量 - C++ std::function variable with varying arguments 是否可以在 C++ 中创建一个函数来接收无限数量的相同类型(或至少大量)的参数? - Is it possible to create a function receiving an infinite amount of arguments of the same type (or at least a good amount) in c++? C ++变量参数 - C++ variable arguments C++ Function 具有可变数量和类型的 arguments 作为另一个 ZC1C425268E683854F4B50741ZA7 的参数 - C++ Function with variable number and types of arguments as argument of another function 是否可以通过全局变量定义具有可变数量的参数的函数中的参数数量 - Is it possible to define the amount of arguments in a function with variable number of arguments by a global variable C ++静态编译带有可变数字或参数的函数 - C++ static compilation of function with a variable number or arguments c ++传递带有可变数量参数的函数作为其他函数的参数 - c++ passing functions with variable number of arguments as argument to other function 如何在Boost Python中公开带有可变参数的C ++函数 - How to expose a c++ function taking variable arguments in boost python C ++:函数指向具有可变数量参数的函数 - C++: Function pointer to functions with variable number of arguments
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM