用整数的初始化列表初始化长双精度数的向量 [英] 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)
{}
};
这不会编译,因为以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_list
是long 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屋!