1

std::valarray< double > myArray(3) produces a valarray of length 3, initialized to zero.

std::valarray< double > myArray(1,3) produces a valarray of length 3, initialized to one.

std::valarray< double > myArray(0,3) produces error: call to constructor of 'std::valarray<double>' is ambiguous.

I can of course use myArray(3) and add a comment confirming that this is initialized to zero, but for my own understanding I was hoping someone could explain why this is ambiguous--does it conflict with another constructor in a way that I have missed?

sudo make install
  • 5,629
  • 3
  • 36
  • 48

1 Answers1

4

Your third call conflicts with the constructor valarray (const T* p, size_t n);. This is because 0 is as easily convertible to the NULL pointer as it is to a double. You could fix this by explicitly stating to use a double:

std::valarray< double > myArray((double)0,3)
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
  • Thanks, very clear! Do you know, additionally, if there is a performance benefit to using the default or explicit versions? – sudo make install Sep 10 '14 at 14:46
  • 1
    I did some quick benchmarking. With 100,000,000 iterations and no optimisation, the default version ran for 3.9 seconds and the explicit for 4.0 seconds. So the default is slightly faster, but the difference is negligible and would probably be eliminated with a higher `-O` level. (I need to leave now, but you can check that yourself) – TartanLlama Sep 10 '14 at 15:01