On May 9, 8:01 pm, "Dominic Connor, Pimp" <(E-Mail Removed)>

wrote:

> I've got a bit of code that shows which bits of a variable are 1 or 0

> (OK, I'm making assumptions about 8 bit bytes and significance.)

> But what I want to do is only allow this template to be instantiated

> for base types, not classes.

> I am averse to RTTI for this, but I keep thinking there's a bit of

> syntactic sugar that will do it cleanly.

> Solutions of the form "classes are bigger than 64 bits so reject them"

> don't count

> template <typename T> string DumpBits (T x)

> {

> unsigned int mask=1;

> int i;

> string s;

>

> for ( i= 0; i != sizeof(x)*8; i++, mask *=2)

> {

> mask & x ? s = "1" + s : s = "0" + s;

> }

> return s;

>

> }
For starters, why not write the function something like:

template< typename T >

std::string

dumpBits( T value )

{

std::string result ;

while ( result.size() < sizeof( T ) * CHAR_BIT ) {

result += (value & 1 == 0) ? '0' : '1' ;

// or: result += (value & 1) + '0' ;

value >>= 1 ;

}

std::reverse( result.begin(), result.end() ) ;

return result ;

}

This will reject anything for which & or >> isn't defined, which

means anything that isn't either an integral type or designed to

behave like an integral type. Most likely, that's sufficient.

(Of course, the error message isn't very pretty. But then, is

it ever, when you use templates?)

--

James Kanze (GABI Software) email:(E-Mail Removed)

Conseils en informatique orientée objet/

Beratung in objektorientierter Datenverarbeitung

9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34