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}

Share the Post:
data observability

Data Observability Explained

Data is the lifeblood of any successful business, as it is the driving force behind critical decision-making, insight generation, and strategic development. However, due to its intricate nature, ensuring the

Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved