繁体   English   中英

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

[英]Variable amount of function arguments in C++

因此,在C中,标准方式是stdarg.h。 但我希望提出类似以下的内容:

template<int A>
class MyClass {
public:
    MyClass(...) {
        // fill each value of array with an argument.
    };

    virtual ~MyClass() { };
private:
    float array[A];
};

显然,这种想法是,对于每种可能的论点,都不应有不同的结构。 有什么建议,标准方法吗?

谢谢,

朱利安。

在C ++ 11中,可以将std :: initializer_list构造函数用于这种情况。 这允许这种类型的初始化:

MyClass<5> x{1,2,3,4,5};

尽管您必须定义尺寸不匹配时会发生什么。 但是对于这类静态大小的数组,值得研究std :: array 当初始值设定项的尺寸与自己的尺寸不匹配时,它们具有明确定义的行为。

您需要使用initializer_list

explicit MyClass(std::initializer_list<T> list_args){
    // fill each value of array with an argument.
};

如果您无权访问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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM