template <typename T>
class v3 {
private:
T _a[3];
public:
T & operator [] (unsigned int i) { return _a[i]; }
const T & operator [] (unsigned int i) const { return _a[i]; }
operator T * () { return _a; }
operator const T * () const { return _a; }
v3() {
_a[0] = 0; // works
_a[1] = 0;
_a[2] = 0;
}
v3(const v3<T> & v) {
_a[0] = v[0]; // Error 1 error C2666: 'v3<T>::operator []' : 2 overloads have similar conversions
_a[1] = v[1]; // Error 2 error C2666: 'v3<T>::operator []' : 2 overloads have similar conversions
_a[2] = v[2]; // Error 3 error C2666: 'v3<T>::operator []' : 2 overloads have similar conversions
}
};
int main(int argc, char ** argv)
{
v3<float> v1;
v3<float> v2(v1);
return 0;
}
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
I didn't see it untill James McNellis posted the full error message, but the ambiguity is not between the two
v3::operator[]()
functions as it appears to be.Instead, since there is no exact match between argument types, the compiler can't decide whether to:
a) Use
v3::operator[](unsigned int) const
, thereby converting the int argument to unsigned, orb) Use the
v3::operator const T*() const
conversion followed by the built-in array indexing operator.You can avoid this by making the operator[] arguments int's rather than unsigned ints. But a better solution would be to avoid an implicit conversion to T* and instead provide a Data() function that did that explicitly.
In simple terms: the compiler doesn't know whether to convert
v
toconst float*
and then use theoperator[]
for a pointer, or to convert0
tounsigned int
and then use theoperator[]
forconst v3
.Fix is probably to remove the
operator[]
. I can't think of anything it gives you that the conversion operator to T* doesn't already. If you were planning to put some bounds-checking inoperator[]
, then I'd say replace the conversion operators withgetPointer
functions (since in general you don't want to implicitly convert a safe thing to an unsafe thing), or do whatstd::vector
does, which is that users get a pointer with&v[0]
.Another change that lets it compile, is to change
operator[]
to take anint
parameter instead ofunsigned int
. Then in your code, the compiler unambiguously chooses the interpretation with no conversion. According to my compiler, there is still no ambiguity even when using an unsigned index. Which is nice.