3

I am developing lightweight parser as C++ h-file template library.

Gramma is described in specific BNF-like notation using overloaded operators on some classes which should be enumerated somehow. I need just one global variable as some counter performing it.

I do not want to use extern int var; in h-file and int var; in cpp-file because all my stuff in single header file and now the user just needs to include it.

I can declare static int var; in header file but copy of this variable appears in all object files where my header file is included.

Is it OK for template library? Any suggestions?

kenorb
  • 155,785
  • 88
  • 678
  • 743

1 Answers1

1

As already mentioned you can use singleton pattern. This version doesn't require definition of static member in template cpp file.

template <typename T> class Tmpl
{
public:
    static Tmpl<T>& GlobalInstance()
    {
        static Tmpl<T> m_Singleton;
        return m_Singleton;
    };
};
elanius
  • 487
  • 2
  • 19