MasonMac
MasonMac

Reputation: 147

How to push int/float variadic arguments into vector<double>?

class Entity
{
private:
    std::vector<double> m_Numbers;
public:
    template<typename... Args>
    Entity(Args... parameters)
        : m_Numbers{ parameters... } {}
};

int main()
{
    Entity e1(5, 7);
}

Unexpectedly, the vector did not convert the ints into doubles and threw out an error:

C2398 | Element '0': conversion from 'int' to '_Ty' requires a narrowing conversion`

Is there a way to have std::vector<double> accept any number type (e.g. int/float/uint32_t)?

Upvotes: 4

Views: 177

Answers (3)

asmmo
asmmo

Reputation: 7100

With brace initialization, implicit conversions aren't allowed, but you can use push_back and the parameter pack expansion, as follows.

class Entity
{
private:
    std::vector<double> m_Numbers;
public:
    template<typename... Args>
    Entity(T first, Args... parameters){
        (m_Numbers.push_back(parameters),...);
    }
};

Upvotes: 1

Stephen Newell
Stephen Newell

Reputation: 7863

You can perform an explicit conversion to double.

    : m_Numbers{static_cast<double>(parameters)... } {}

The problem is that std::vector's constructor requires doubles since that's the type it stores. Since you're constructing with brace initialization, implicit conversions aren't allowed, hence your warning (although with gcc I only get a warning).

Upvotes: 4

MasonMac
MasonMac

Reputation: 147

Using : m_CurrentNumbers{ static_cast<double>(parameters)... } {} worked to explicitly convert all the arguments into double.

Upvotes: 1

Related Questions