3

I'm trying to figure this out, and, it's really annoying me. I have a function that converts either an array or a vector into a vector of complex numbers, but, I do not know how it would be possible for the function to be able to accept both double arrays, as well as double vectors. I've tried using templates, but, this does not seem to work.template

template<typename T>
vector<Complex::complex> convertToComplex(T &vals)
{

}


Value::Value(vector<double> &vals, int N) {

};


Value::Value(double *vals, int N) {


};

What I am hoping for is this:

int main()
{
   double[] vals = {1, 2, 3, 4, 5};
   int foo = 4;
   Value v(vals, foo); // this would work and pass the array to the constructor, which would
                  // then pass the values to the function and covert this to a 
                  //   vector<complex>
}

I could do the same for a vector as well.. I don't know whether or not templates are the right approach for this.

4

2 回答 2

3

您可以使您的函数和构造函数成为一个带有两个迭代器的模板:

template<typename Iterator>
vector<Complex::complex> convertToComplex(Iterator begin, Iterator end)
{

}

class Value
{
 public:
  template <Iteraror>
  Value(Iterator begin, Iterator end)
  {
    vector<Complex::complex> vec = comvertToComplex(begin, end);
  }
  .... 
};

然后

double[] vals = {1, 2, 3, 4, 5};
Value v(std::begin(vals), std::end(vals)); 

std::vector<double> vec{1,2,3,4,5,6,7};
Value v2(v.begin(), v.end());

我省略foo了,因为我不太清楚它的作用是什么。

于 2013-07-03T20:30:48.527 回答
2

如果您只想支持双打,则无需在此处定义模板函数。你应该这样做,它更简单:

vector<Complex::complex> convertToComplex(const double* array, size_t len)
{
  // ... your implementation
}

vector<Complex::complex> convertToComplex(const vector<double>& v, size_t len)
{
  return convertToComplex(v.data(), len);
}

而已!

于 2013-07-03T20:36:37.617 回答