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:
Share on facebook
Share on twitter
Share on linkedin


The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS