You can use type_traits and static_assert to prevent the instantiation of your class using the const type.
#include <type_traits> template <class T> class Vector2D { static_assert( !std::is_const<T>::value, "T must be non-const" ); TX; TY; 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 }
In addition, I changed my class to use member initialization lists in the constructor to initialize member variables. And I made x and y private .
source share