Reputation: 147
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 int
s into double
s 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
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
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 double
s 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
Reputation: 147
Using : m_CurrentNumbers{ static_cast<double>(parameters)... } {}
worked to explicitly convert all the arguments into double.
Upvotes: 1