简体   繁体   中英

Initialize Vector of Long Doubles with Initialization List of Ints

Suppose I have a simple class:

class Pvector
{
  private:
  std::vector<long double> point_list;

  public:
  Pvector(std::initializer_list<long double> coords) : point_list(coords)
  {}
  Pvector(std::initializer_list<int> coords) : point_list(coords)
  {}
};

This will not compile because the std::vector templated on type long double cannot initialize itself from an initialization list templated on type int . This is rather inconvenient, however, because with the second constructor removed, I cannot do the following in my code:

Pvector piece_movement({E.X - S.X, E.Y - S.Y, E.Z - S.Z});

This is because the resultant type from my arithmetic operations is of type int . So I seem to be in a conundrum. I'd like to be able to pass integers directly into the constructor for Pvector , but I still want point_list to be of type long double and (somehow) be initialized with the integers I pass in. How might I go about doing this?

Solution 1

You can remove the second constructor and still be able to construct PVector using

 Pvector v2{1, 2};

Example:

#include <initializer_list>
#include <vector>

class Pvector
{
  private:
  std::vector<long double> point_list;

  public:
  Pvector(std::initializer_list<long double> coords) : point_list(coords)
  {}
};

int main()
{
   Pvector v1{1.0, 2.0};
   Pvector v2{1, 2};
}

Solution 2

Use a template constructor in Pvector and the use the constructor of std::vector that takes two iterators to initialize point_list .

#include <initializer_list>
#include <vector>

class Pvector
{
  private:
  std::vector<long double> point_list;

  public:

  // This is not necessary any more.
  // Pvector(std::initializer_list<long double> coords) : point_list(coords){}

  template <typename T>
  Pvector(std::initializer_list<T> coords) : point_list(coords.begin(), coords.end()){}
};

int main()
{
   Pvector v1{1.0, 2.0};
   Pvector v2{1, 2};
}

You probably get a narrowing conversion warning , right?

Stolen from here :

C++11 8.5.4/7 A narrowing conversion is an implicit conversion [...] from an integer type [...] to a floating-point type, except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type.

So you will get this warning every time you convert a non constant integer expression, ie a variable, into a floating-point type. Whether the value will fit into the mantissa of the corresponding type will depend on the type (float, double, long-double) and the implementation of the type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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