I am trying to run std :: enable_if for the first time and struggling. Any recommendations would be appreciated.
As an example of toys, this is a simple static vector class for which I want to define a copy constructor, but the behavior depends on the relative sizes of the vectors:
- just copy the data into a smaller or the same size vector.
- copy the data to a larger vector and then put the rest with zeros
So the vector class:
template <size_t _Size> class Vector { double _data[_Size]; public: Vector() { std::fill(_data, _data + _Size, 0.0); } const double* data() const { return _data; } ... };
The copy constructor should support something like this by copying the first 2 elements of v3 to v2:
Vector<3> v3; Vector<2> v2(v3);
I tried the copy constructor for behavior 1. for example, which compiles:
template <size_t _OtherSize, typename = typename std::enable_if_t<_Size <= _OtherSize>> Vector(const Vector<_OtherSize>& v) : Vector() { std::copy(v.data(), v.data() + _Size, _data); }
but the compiler cannot distinguish this from behavior 2. although the enable_if conditions are mutually exclusive.
template <size_t _OtherSize, typename = typename std::enable_if_t<_OtherSize < _Size>> Vector(const Vector<_OtherSize>& v) : Vector() { std::copy(v.data(), v.data() + _OtherSize, _data); std::fill(_data + _OtherSize, _data + _Size, 0.0); }
I also tried to include enable_if in the argument instead, but could not infer the value of _OtherSize:
template <size_t _OtherSize> Vector(const typename std::enable_if_t<_Size <= _OtherSize, Vector<_OtherSize>> & v) : Vector() { std::copy(v.data(), v.data() + _Size, _data); }
What is the best way to do this (using enable_if, not a simple if statement)?
thanks