Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template Class C++ - exclude some types

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;
    };
}
like image 589
Tony B Avatar asked Jan 18 '23 03:01

Tony B


2 Answers

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.

like image 73
enobayram Avatar answered Jan 25 '23 01:01

enobayram


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.

like image 29
Praetorian Avatar answered Jan 25 '23 00:01

Praetorian