views:

53

answers:

3

Hi,

In my library, I have several initialize() and cleanup() functions, for different modules it depends on.

To make this part more safe to use, I decided to follow the RAII rule and built up an Initializer template class, that takes two functions as parameters:

// initializer.hpp (include guards omitted)

template <void initialize(), void cleanup()>
class Initializer
{
  // Does something, but that's not relevant
};

Now, in my xml.hpp file I have this:

// xml.hpp (include guards omitted)

namespace xml
{       
  void initialize();
  void cleanup();

  typename ::Initializer<&initialize, &cleanup> Initializer;
}

This compiles fine but fails on linking because several files include xml.hpp and gcc complains that there are multiple definitions for xml::Initializer.

What can I do to solve this ?

A: 

include your xml.hpp code inside these macros

#ifndef XML_HPP
#define XML_HPP

// Include code here

#endif
Pardeep
Thanks but I already have include guards. I just omitted them for simplicity's sake.
ereOn
+2  A: 
typename ::Initializer<&initialize, &cleanup> Initializer;

This is an explicit instantiation. Please put it in one and only one translation unit

Chubsdad
As @Charles Bailey pointed out, it was a stupid typo... I meant `typedef`. Still, thanks. I just need more coffee I guess... +1 ;)
ereOn
But I guess the error was about multiple definitions. If it was a typename issues, it would be a syntax error. I am confused
Chubsdad
My compiler didn't complain about a syntax error. It would have been easier to spot, indeed. My question includes a simplified example of my code, perhaps this is the reason why it passed compilation.
ereOn
+3  A: 
namespace xml
{       
  void initialize();
  void cleanup();

  typename ::Initializer<&initialize, &cleanup> Initializer;
}

typename is illegal here, it is only allowed in template definitions. You meant typedef!

namespace xml
{       
  void initialize();
  void cleanup();

  typedef ::Initializer<&initialize, &cleanup> Initializer;
}
Charles Bailey
Indeed I meant `typedef` ;) Thanks for noticing it !
ereOn