I am using the latest version of MSVC with Visual Studio 2015 Community Edition, and I am having some issues with template specialisation and operator overloading.
I have the following (header only) vector class snippet. I have excluded unnecessary code (i.e. identical specialisations for vec2 and vec4).
template <typename T, int n>
struct VectorN
{
T data[n];
T& operator[](const int i);
};
template <typename T, int n>
T& VectorN<T, n>::operator[](const int i)
{
static_assert(i >= 0 && i < n, "Index out of range");
return data[i];
}
template <typename T, int n>
std::ostream& operator<<(std::ostream& os, const VectorN<T, n>& vec)
{
for (auto i = 0; i < n; ++i)
{
os << vec[i];
}
return os;
}
With the following specialisation:
template <typename T>
struct VectorN<T, 3>
{
union
{
T data[3];
struct
{
T x, y, z;
};
};
};
typedef VectorN<int, 3> Vec3i;
typedef VectorN<float, 3> Vec3f;
The main function that I am compiling is:
int main(int argc, char *argv[])
{
Vec3f vec{ 0, 1, 2 };
std::cout << vec << std::endl;
char dump;
std::cin >> dump;
std::cin.clear();
return 0;
}
I would expect that it works, however, I get an Error: C2676 binary '[': 'const VectorN<float,3>' does not define this operator or a conversion to a type acceptable to the predefined operator
I believe that the ostream operator is working as intended, but that the indexing operator is not. Is there anything that I am doing that is obviously wrong, or does the current MSVC simply not support what I am trying to do?
Aucun commentaire:
Enregistrer un commentaire