Need assistance translating this C++ template

John via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Oct 27 15:43:22 PDT 2014


Howdy,

I stumbled across a tiny NES emulator written in C++ 
(http://bisqwit.iki.fi/jutut/kuvat/programming_examples/nesemu1/nesemu1.cc) 
that I feel compelled to make even tinier with some D magic. I am 
having trouble with a nested template in the code.

The C++ code:

// Bitfield utilities
template<unsigned bitno, unsigned nbits=1, typename T=u8>
struct RegBit
{
     T data;
     enum { mask = (1u << nbits) - 1u };
     template<typename T2>
     RegBit& operator=(T2 val)
     {
         data = (data & ~(mask << bitno)) | ((nbits > 1 ? val & 
mask : !!val) << bitno);
         return *this;
     }
     operator unsigned() const { return (data >> bitno) & mask; }
     RegBit& operator++ ()     { return *this = *this + 1; }
     unsigned operator++ (int) { unsigned r = *this; ++*this; 
return r; }
};

My D implementation thus far:

// To avoid type confusion...
alias u8 = uint_least8_t;
alias u32 = uint_least32_t;

template RegBit(uint bitno, uint nbits = 1, T = u8) {
     T data;
     enum { mask = (1u << nbits) - 1u }

     // FIXME: Nested template frustration here... HELP
     void opAssign(T2 val)
     {
         data = (data & ~(mask << bitno)) | ((nbits > 1 ? val & 
mask : !!val) << bitno);
         return *this;
     }

     auto opCall() { return (data >> bitno) & mask; }
     ref RegBit opUnary(string s)() if (s == "++") { return *this 
= *this + 1; }
     ref RegBit opUnary(string s)(int) if (s== "++") { uint r = 
*this; ++*this; return r; }
}

Any push in the right direction would be greatly appreciated. I'm 
just trying to get a D implementation up and running before I 
start making this smaller and more intuitive.


More information about the Digitalmars-d-learn mailing list