Need assistance translating this C++ template
anonymous via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Oct 27 16:19:42 PDT 2014
On Monday, 27 October 2014 at 22:43:23 UTC, John wrote:
> The C++ code:
>
> // Bitfield utilities
> template<unsigned bitno, unsigned nbits=1, typename T=u8>
> struct RegBit
> {
[...]
> template<typename T2>
> RegBit& operator=(T2 val)
[...]
> };
>
> My D implementation thus far:
[...]
> template RegBit(uint bitno, uint nbits = 1, T = u8) {
You're missing the struct here. Add some (template) parameters to
a struct, and it becomes a struct template:
struct RegBit(uint bitno, uint nbits = 1, T = u8)
[...]
> // FIXME: Nested template frustration here... HELP
> void opAssign(T2 val)
Similarly, add another set of (template) parameters to a
function/method, before the runtime parameters, and it becomes a
function/method template:
void opAssign(T2)(T2 val)
[...]
> }
Those "slap another set of parameters on, and it's a template"
syntaxes, are sugar for the longer "eponymous member" variant:
struct Foo(T) {}
is equivalent to
template Foo(T)
{
struct Foo /* same name as the template */
{
/* ... */
}
}
Works with structs, classes, functions, etc.
So if you wanted to spell the templates out, it would look like
this:
template RegBit(uint bitno, uint nbits = 1, T = u8)
{
struct RegBit
{
/* ... other members of RegBit ... */
template opAssign(T2)
{
void opAssign(T2 val)
{
/* ... implementation of opAssign ... */
}
}
/* ... other members of RegBit ... */
}
}
More information about the Digitalmars-d-learn
mailing list