Signed and unsigned template type parameters

B

Bob Hairgrove

Hello,

Consider the member function length() in the following declaration:

enum range_direction { NONE, FORWARD, REVERSE };

template<typename E, typename D>
class Range
{
typedef E element_type;
typedef D distance_type;
public:
Range();
Range( const E & startT
, const E & endT
, bool directed = true);
Range( const E & startT
, const D & lengthT
, bool directed
, range_direction direction);
Range( const Range & );
Range& operator=( const Range & );
~Range() { ; }

const E & begin() const { return m_start; }
const E & end() const { return m_end; }
D length() const { return (m_end - m_start); }
// etc.
private:
E m_start;
E m_end;
bool m_directed;
};

How can I prohibit template instantiations with distance_type of
unsigned integral types? E.g. Range<double, unsigned int>?

It can be OK if the Range has no implicit direction; however, if
REVERSE is specified, then (m_end - m_start) should reflect that.

Of course, for user-defined types, it is up to the application to
define D such that E(endElem) - E(startElem) reflects the direction in
the D which is returned (or pass direction=false to the appropriate
constructor).

But is it possible to prevent unsigned D for built-in integral types?
Do I need to create template specializations for each type (i.e.
unsigned char, unsigned short, unsigned int, etc.)? I could do that
and throw an exception, but it would be nicer to have a compile-time
check.

Thanks.
 
J

John Harrison

Bob Hairgrove said:
Hello,

Consider the member function length() in the following declaration:

enum range_direction { NONE, FORWARD, REVERSE };

template<typename E, typename D>
class Range
{
typedef E element_type;
typedef D distance_type;
public:
Range();
Range( const E & startT
, const E & endT
, bool directed = true);
Range( const E & startT
, const D & lengthT
, bool directed
, range_direction direction);
Range( const Range & );
Range& operator=( const Range & );
~Range() { ; }

const E & begin() const { return m_start; }
const E & end() const { return m_end; }
D length() const { return (m_end - m_start); }
// etc.
private:
E m_start;
E m_end;
bool m_directed;
};

How can I prohibit template instantiations with distance_type of
unsigned integral types? E.g. Range<double, unsigned int>?

I would use the boost concept check library

#include <boost/concept_check.hpp>

template<typename E, typename D>
class Range
{
BOOST_CLASS_REQUIRE(D, boost, SignedIntegerConcept);

...

john
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top