i recently created a template class which is working fine.
Now i wanted to use "const int" (for example), but dynamic binding is forbidden.
is there a possibility to exclude the type const int?
this is my class; the compiler will drop out an error for the 2nd constructor. i've seen that one coming, but i just don't know how to modify it the correct way - and ideas?
template <class T>
class Vector2D
{
public:
T X;
T Y;
Vector2D()
{
X = 0;
Y = 0;
};
Vector2D(T x, T y)
{
X = x;
Y = y;
};
}
Use member initialization lists:
template <class T>
class Vector2D
{
public:
T X;
T Y;
Vector2D(): X(0), Y(0)
{
};
Vector2D(T x, T y):X(x),Y(y)
{
};
}
That should solve your current problem with const int
. If you're really interested in forbidding a certain type in general, take a look at boost::enable_if.
You can use type_traits
and static_assert
to prevent instantiation of your class using a const
type.
#include <type_traits>
template <class T>
class Vector2D
{
static_assert( !std::is_const<T>::value, "T must be non-const" );
T X;
T Y;
public:
Vector2D() : X( 0 ), Y( 0 )
{
}
Vector2D(T x, T y) : X( x ), Y( y )
{
}
};
int main()
{
Vector2D<int> v1( 10, 20 );
Vector2D<const int> v2( 10, 20 ); //static_assert fails
}
Also, I've changed your class to use member initialization lists in the constructor to initialize member variables. And I've made x
and y
private
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With