I am writing a simple vector class and I would like to have some member functions that are only available in vectors of certain lengths (cross product for a 3 element vector for example). I stumbled across std::enable_if and it looks like it may be able to do what I want, but I don't seem to be able to get it working correctly.
#include <iostream>
#include <type_traits>
template<typename T, unsigned int L>
class Vector
{
private:
T data[L];
public:
Vector<T,L>(void)
{
for(unsigned int i = 0; i < L; i++)
{
data[i] = 0;
}
}
T operator()(const unsigned int i) const
{
return data[i];
}
T& operator()(const unsigned int i)
{
return data[i];
}
Vector<typename std::enable_if<L==3, T>::type, L> cross(const Vector<T,L>& vec2) const
{
Vector<T,L> result;
result(0) = (*this)(1) * vec2(2) - (*this)(2) * vec2(1);
result(1) = (*this)(2) * vec2(0) - (*this)(0) * vec2(2);
result(2) = (*this)(0) * vec2(1) - (*this)(1) * vec2(0);
return result;
}
};
int main(void)
{
Vector<double,3> v1;
Vector<double,3> v2;
Vector<double,3> v3;
//Vector<double,4> v4;
v1(0) = 1;
v1(1) = 2;
v1(2) = 3;
v2(0) = 4;
v2(1) = 5;
v2(2) = 6;
v3 = v1.cross(v2);
std::cout << v3(0) << std::endl;
std::cout << v3(1) << std::endl;
std::cout << v3(2) << std::endl;
return 0;
}
The code above compiles and runs correctly, however if I uncomment the declaration of Vector<double,4> v4
I get the following error at compilation:
vec.cpp: In instantiation of ‘class Vector<double, 4u>’:
vec.cpp:46:22: required from here
vec.cpp:29:59: error: no type named ‘type’ in ‘struct std::enable_if<false, double>’
Is someone able to point out where I am going wrong?