October 21, 2024
Chicago 12, Melborne City, USA
templates

Variadic template class: Allow for float and int arguments cast to float?


I have the following class:

template <size_t N, float... Lam> requires (sizeof...(Lam) == N)
class Spectrum {
public:
    Spectrum() : wavelengths{ static_cast<float>(Lam)... }
    {
        values.fill(0.f);
    };

    template <IsNumeric T>
    Spectrum(T v) : wavelengths{ static_cast<float>(Lam)... }
    {
        values.fill(static_cast<float>(v));
    };

    template <IsNumeric... T> requires (sizeof...(T) == N)
    Spectrum(T... v) : wavelengths{ static_cast<float>(Lam)... }, values { static_cast<float>(v)... } 
    { };

... // Other methods/overloads that aren't relevant here

private:
    std::array<float, N> values;
    const std::array<float, N> wavelengths;
};

I can then call this using:

Spectrum<3, 450.f, 500.f, 600.f> color{ 1,2,3 };

And it behaves as expected (the wavelengths are populated with 450.f, 500.f, 600.f and the values are populated with 1.f, 2.f, 3.f.

I would like to be able to allow users to instead call:

Spectrum<3, 450, 500, 600> color{1,2,3};

in this case, 450 is an int, so I’d need it to be cast to a float, in a similar way to what I already do in the constructor templates. I’m just not sure if a similar idea can be expressed in the class template itself.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video