向量的隐式转换从一个类型到另一个c ++ [英] implicit conversion of vector from one type to another c++
本文介绍了向量的隐式转换从一个类型到另一个c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否可以将一种类型的向量转换成另一种类型的向量 implicitly
即一些方法使这个代码工作(显然这是一个简化的问题,我想做什么)
std :: vector< int> intVec;
没有,没有转换(隐式或其他)
intVec.push_back(1);
std :: vector< double> doubleVec = intVec;
std :: vector< double> doubleVec2;
doubleVec2 = intVec;
您可以从迭代器范围初始化它:
std :: vector< double> doubleVec(intVec.begin(),intVec.end());
可能将此功能包装在一个函数中:
template< typename To,typename From>
到container_cast(从&& amp; from){
using std :: begin;使用std :: end; //启用Koenig查找
return To(begin(from),end(from));
}
auto doubleVec = container_cast< std :: vector< double>>(intVec);
Hey guys was hoping you could help me out.
I want to know if it is possible to convert a vector of one type to another implicitly
i.e some way to make this code work (obviously this is a simplified problem of what I am trying to do)
std::vector<int> intVec; intVec.push_back(1); std::vector<double> doubleVec = intVec; std::vector<double> doubleVec2; doubleVec2 = intVec;
解决方案No, there is no conversion (implicit or otherwise) between different vector types.
You could initialise it from an iterator range:
std::vector<double> doubleVec(intVec.begin(), intVec.end());
perhaps wrapping this in a function:
template <typename To, typename From> To container_cast(From && from) { using std::begin; using std::end; // Koenig lookup enabled return To(begin(from), end(from)); } auto doubleVec = container_cast<std::vector<double>>(intVec);
这篇关于向量的隐式转换从一个类型到另一个c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文