Search code examples
c++templatesnested-class

How can the non-templated struct nested inside of a templated outer class access static members of the outer class?


I swear I've searched all over the Internet and SO for this exact problem, but couldn't find any solutions.

Here's the setup:

template <typename T>
class Foo {
  static bool bar;

public:
  struct Baz {
    void quux() {
      // I want to access bar here
    }
  };
  // friend typename struct Foo<T>::Baz;
  // The above works, but I'm not sure if it's what I need?
};

Is what I'm trying to do possible?


Solution

  • The access is not a problem, just use Foo<T>::bar within Baz. I think that the bigger problem is that you need to allocate storage for Foo<T>::bar. This means that in your Foo.cpp file you'd have to actually instantiate all the templates you might think of using. For example:

    template <typename T>
    class Foo {
      static bool bar;
    public:
      struct Baz {
        void quux() {
          // I want to access bar here
            Foo<T>::bar = true;
        }
      };
      static bool getBar() { return bar; }
    };
    
    // allocating storage for bars
    template<>
    bool Foo<int>::bar = false;
    template<>
    bool Foo<double>::bar = false;
    
    int main() {
        Foo<int> fint;
        Foo<double> fouble;
        cout << Foo<int>::getBar() << " " << Foo<double>::getBar() << '\n';
        Foo<int>::Baz baz;
        baz.quux(); // alter int bar
        cout << Foo<int>::getBar() << " " << Foo<double>::getBar() << '\n';
    }
    

    Live demo