Reputation: 31
I've been working on a small library collection, and in my n-dimensional geometric vector template class, I've run into an issue between two constructors. The constructor VectorN( t data[n] )
clashes with constructor VectorN( t value )
, and I get the error:
More than one instance of constructor ___ matches the argument list".
I understand why this is occuring, but a solution eludes me. The issue only occurs when I attempt to instantiate the class using VectorN(0)
, but when value
is anything other than 0 the correct constructor is used. What can I do to fix this?
Upvotes: 0
Views: 130
Reputation: 44238
You improperly declared constructor that accepts C style array - you are loosing size. If you do that correctly:
template <class T>
class VectorN {
public:
template<std::size_t N>
VectorN( T (&array)[N] );
...
};
then problem with 0 would disappear.
Upvotes: 3
Reputation: 480
If you pass an array like t data[n]
, actually you just pass a pointer on the first element of the array. So your first constructor is equal to VectorN(t* data)
. So now when you call the constructor with zero, the compiler might as well think you want to pass the null-pointer.
I would recommend you to clearly distinguish your constructors. So for example since you have a n-dimensional vector, you have to specify the n somewhere. You could do a constructor like: VectorN(t* data, int n)
. Than it is definitely clear where you want to use what constructor.
Upvotes: 0
Reputation: 146910
The problem is that 0 is a valid null pointer constant, which is a valid T* (which is what t data[n] actually is under the hood). If you really want to take raw C arrays, use a reference to the array- this is strongly typed and safe(r).
Also, raw C arrays are shit. std::array
is for when you want to not segfault.
Upvotes: 5