Computer Chess Club Archives


Search

Terms

Messages

Subject: Re: CPP related question on double code (B/W)

Author: Daniel Clausen

Date: 07:07:38 11/24/03

Go up one level in this thread


On November 24, 2003 at 09:49:29, Reinhard Scharnagl wrote:

>Would it not be better to place the template into a header file?
>And then to implement it twice?
>
>Regards, Reinhard.

I'm not quite sure I understand what you mean here. But let me try to answer
anyhow. *giggles*

The testprogram I posted was just a little example to illustrate the usage of
these kind of templates. In a real project the template would surely be in a
seperate file. Basically you have two options here:

(a)
Put the whole template code in a header file (protect it with needed ifdef of
course) and include it whereever you need an "instance" of such the template
function.

(b)
Put the template implementation in a C++ file and only put the template
declaration in the header file. The problem here is that the linker won't be
able to find the templates you instantiate somewhere else. This can be helped by
instantiating them in the same C++ file as the template body is, see example
below:


--- File Stuff.h ---
#ifndef STUFF_H
#define STUFF_H

template <int colour> void print(void);

#endif /* STUFF_H */


--- File Stuff.cxx ---
#include "Stuff.h"
#include <iostream>

template <int colour> void print(void)
{
   std::cout << colour << std::endl;
}

// The function 'linkTemplates' will never be called but makes sure that
// all needed template instances are created whenever this c++ file is compiled.
void linkTemplates(void)
{
    print<0>();
    print<1>();
}


--- File main.cxx ---
#include "Stuff.h"


int main(void)
{
   print<0>();
   print<1>();

   return 0;
}


The problem with this approach is that you will have to know in 'Stuff.cxx'
which templates to instantiate. I don't like code in headerfiles but this is
also a problem. Not sure which version I prefer here...


Hope this answers your question.

Sargon

PS. As other posters noted, this approach might not work with VC++.



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.