Computer Chess Club Archives


Search

Terms

Messages

Subject: Re: Colourspecific code (C++ and templates/traits)

Author: Russell Reagan

Date: 20:05:46 11/26/03

Go up one level in this thread


On November 26, 2003 at 17:30:03, Daniel Clausen wrote:

>Using templates/traits, I would like to replace the call
>
>   uint64_t bb = AttackTable::whitePawnAT[42];
>
>with something like
>
>   uint64_t bb = AttackTable::ColorTraits<White>::pawnAT[42];

The advantage of the code that I posted was that you only had to write one
function, but you had to create two ColorTraits structs. In other words, you
specified the small portions of the function that would differ in the structs,
then write one function. In this case it is really nothing more than a syntax
issue. I could do:

Bitboard PawnAttacks (int color, int square);
Bitboard attacks = PawnAttacks(white, e4);

The return value of the function call above will be known at compile time, so
this should be just as fast as using the template. You could write a templated
version like:

Bitboard attacks = PawnAttacks<white>(e4);

I'm not sure there is a lot to be gained here. The first version which takes a
color as an argument seems more flexible to me, because you can either give it a
constant value such as white or black and have it be resolved at compile time,
or you could give it variables and it will still work, while the templated
version would not work with variables. Something like this:

Bitboard PawnAttacks (int color, int square)
{
    // You could have these arrays outside of this function as well, such as
    // in a color traits struct.
    static const int leftAttackDirection[2] = { 7, -7 };
    static const int rightAttackDirection[2] = { 9, -9 };
    // Then use the arrays like: forwardAttackDirection[color]
    // ...
}

Then if you pass a constant color or square, the compiler may be able to do some
partial evaluation of the return value. I am not particuarly knowledgable about
the details of templates however, and there may be some benefit I am
overlooking. The main benefit of templates, I think, is when you specify a type,
as in std::vector<int> v; since you can't pass that kind of type information to
a function (not as efficiently anyway). Also metaprogramming is probably
benefitial, but I've never done much of that myself.



This page took 0 seconds to execute

Last modified: Thu, 15 Apr 21 08:11:13 -0700

Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.