用整数的初始化列表初始化长双精度数的向量 [英] Initialize Vector of Long Doubles with Initialization List of Ints

查看:124
本文介绍了用整数的初始化列表初始化长双精度数的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个简单的课:

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)
  {}
};

这不会编译,因为以long double类型为模板的std::vector不能从以int类型为模板的初始化列表进行初始化.但是,这很不方便,因为删除了第二个构造函数后,我无法在代码中执行以下操作:

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});

这是因为我的算术运算得到的结果类型是int类型.因此,我似乎处于一个难题之中.我希望能够将整数直接传递到Pvector的构造函数中,但是我仍然希望point_listlong double类型,并且(以某种方式)使用传入的整数进行初始化.关于这样做吗?

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?

推荐答案

解决方案1 ​​

您可以删除第二个构造函数,但仍然可以使用

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

 Pvector v2{1, 2};

示例:

#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};
}

解决方案2

Pvector中使用模板构造函数,并使用std::vector的构造函数,该构造函数需要两个迭代器来初始化point_list.

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};
}

这篇关于用整数的初始化列表初始化长双精度数的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆