I never really had a necessity for a global variable in a template (and actually I don't support a design like this very much) but this topic got me curious.
Even though answered, it inspired me trying a different approach. Instead of using inheritance, I came up with this:
class Bar {};
class {
private:
Bar bar;
template <class T> friend class Foo;
} static foobar_singleton;
template <class T>
class Foo
{
public:
static Bar bar() { return foobar_singleton.bar; }
};
To me, the foobar_singleton
works similarly to a 'non-member static private', since its content will be only acessible by the template class Foo. It also avoids inheritance though I am not sure this is an advantadge actually. My solution seems possible to be contained header-only, without necessity about another definition file.
I would like to see what are the opinions about this approach compared to the one utilized as an answer for the thread that got me curious. For instance, some examples of questions I'd like to hear about:
1. Do you see any clear advantadge in my example? Or for that matter, clear disavantadge?
2. Would you advice making bar
attribute a static member and naming the class used as singleton?
3. This reminds any of you of any design pattern? Similar to pimpl
idiom maybe?
4. You see any compiler portability problems? (I've tested it only with MSVC and GCC)
5. I'm right about being a possible header-only implementation? I'm actually not completely sure about the static variable foobar_singleton
Thanks in advance!