Templates and Nested Classes

Templates and Nested Classes

What is the C++ syntax for defining a function that belongs to a nested class that is contained within a template class? For example:

 template class A{  protected:  // nested class  class B  {    void BFunc(Type BFuncVar);    // other stuff for class B  };  // other stuff for class A};

If BFunc is an inline function, everything works. But I cannot figure out what thesyntax should be if I wish to define BFunc outside the class definition. I tried something like:

 templatevoid A::B::BFunc(Type BFuncVar){ ... }

but the linker complained that it couldn’t find the function. (I was using Visual C++ version 6.)

Your code has two omissions.

First, you need to create an instance of the nested class inside the containing template. Otherwise, the inner class is useless.

Second, the nested class’s member function is implicitly declared private. Was that intentional? I doubt it. You cannot call a nonpublic member function of the nested class from its containing class.

The following template definition fixes these two flaws. It works fine on C++ Builder 4. It should work fine on Visual C++ 6.0, too:

 template class A{  protected:  // nested class  class B  {  public: //!!add an explicit access specifier    void BFunc(Type );    // other stuff for class B  } b; //!!create an instance of the nested classpublic:  void f(Type t) {b.BFunc(t);} //!!use nested object  // other stuff for class A};templatevoid A::B::BFunc(Type t) //definition{ t = 0;}int main(){ A aa; aa.f(5); //fine}

See also  How College Students Can Shape the Future of Tech Responsibility

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist