C ++ class template - exclude some types

I recently created a template class that works great.

Now I wanted to use "const int" (for example), but dynamic linking is forbidden.

Is it possible to exclude the type const int?

This is my class; the compiler crosses out the error for the second constructor. I saw that someone came, but I just donโ€™t know how to change it correctly - and ideas?

template <class T> class Vector2D { public: TX; TY; Vector2D() { X = 0; Y = 0; }; Vector2D(T x, T y) { X = x; Y = y; }; } 
+4
source share
3 answers

Use member initialization lists:

 template <class T> class Vector2D { public: TX; TY; Vector2D(): X(0), Y(0) { }; Vector2D(T x, T y):X(x),Y(y) { }; } 

This should solve your current problem with const int . If you are really interested in banning a particular type altogether, see boost :: enable_if .

+4
source

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 .

+3
source

This is what the โ€œVerification Conceptโ€ is for.

Check out http://www.boost.org/doc/libs/1_49_0/libs/concept_check/concept_check.htm

(GCC 4.7 implements it in std :: though, because it is likely to be added to a future standard.)

+2
source

Source: https://habr.com/ru/post/1403149/


All Articles