Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Beginner
Dec 1, 1999

Templates and Nested Classes

Question:
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 the syntax should be if I wish to define BFunc outside the class definition. I tried something like:
 
template
void A::B::BFunc(Type BFuncVar)
{ ... }
but the linker complained that it couldn't find the function. (I was using Visual C++ version 6.)

Answer:
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 class
public:
  void f(Type t) {b.BFunc(t);} //!!use nested object
  // other stuff for class A
};

template
void A::B::BFunc(Type t) //definition
{
 t = 0;
}
int main()
{
 A aa;
 aa.f(5); //fine
}
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date