如何获得除第一个参数外的函数参数?

时间:2020-05-26 16:49:51

标签: c++ variadic-templates variadic-functions

以下是我目前的实现方式:

struct Dual {
    float v;
    std::valarray<float> d;

    Dual(float v, std::valarray<float> d): v(v), d(d) {}
    Dual(float v, float d = 0.f): v(v), d({d}) {}
};

Dual d0{1.f};              // OK.
Dual d1{1.f, 1.f};         // OK.
// Dual d2{1.f, 1.f, 1.f}; // Error. I want this.
Dual d2{1.f, {1.f, 1.f}};  // OK.    I don't want this.

是否可以仅使用一个构造函数?

这样Dual d2{1.f, 1.f, 1.f};也可以。

也许是这样(无法编译):

struct Dual {
    float v;
    std::valarray<float> d;

    Dual(float v, float d...): v(v), d({d...}) {}
};

Dual d0{1.f};
Dual d1{1.f, 1.f};
Dual d2{1.f, 1.f, 1.f}; // I want this.

我应该使用可变参数模板还是std::initilizer_list<>

以及如何使用?

3 个答案:

答案 0 :(得分:2)

您可以编写一个带有各种参量的构造函数,如下所示:

fn($el) => str_replace('o', '0', $el)

这里是demo

使用c ++ 20,您可以将其简化为:

template<typename ...Ts>
Dual(float v, Ts ...ts) : v(v), d({ts...}) {}

与以前的版本相比,它具有一个优点,即构造函数将仅接受浮点值。 (即使以前的版本会警告有关缩小转换范围)。

这里是demo

答案 1 :(得分:2)

类似的事情应该适用于C ++ 20:

class Dual {
    float v;
    std::valarray<float> d;
public:
    Dual(float f, std::floating_point auto... f2)
    : v {f}, d{static_cast<float>(f2)...}  {}
};

int main() {
    Dual f1 {1.5};
    Dual f2 {1.5, 2.5};
    Dual f3 {1.5, 2.5, 3.5};
    // Dual f4 {1.5, 2.5, "3.5"}; // won't compile, type mismatch
}

答案 2 :(得分:1)

除了已存在的答案之外,您还可以使用std::initializer_list(C ++ 11)。不幸的是valarray没有构造函数采用两个迭代器,这使得代码相当笨拙:

#include <valarray>
#include <initializer_list>

struct Dual {
    float v;
    std::valarray<float> d;
    Dual(std::initializer_list<float> in) : v(*in.begin()),
        d(in.size() < 2 ? std::valarray<float>() : 
                          std::valarray<float>(&(*(in.begin()+1)),in.size()-1))
    {}
};


int main() {

    Dual d0{1.f};              // OK.
    Dual d1{1.f, 1.f};         // OK.
    Dual d2{1.f, 1.f, 1.f};    // OK.
}
相关问题