C ++ Template syntax need to pay attention!

xiaoxiao2021-04-01  242

It is not a lot to use C Template recently. However, it is necessary to compile on multiple compilers. When I developed, my development environment was Visual Studio 2005. The compile is of course VC 2005. Compile me a few templates have no problems.

Later, the program needs to be compiled under G multiple versions. There is no problem in G 3.x. But when G - 4.0 has multiple nausea compilation errors. Now, it is listed, I hope to provide some clues to the later person. .

1. Template Class Friend problem.

Many times, a template we hope to pack it with TypeDef.

For example, my ResourceManager and HRESOURCE two template classes .ResourceManager To use the protected member in the HRESOURCE template class. So is a natural definition method:

Template Class HRESOURCE

{

Typedef resourcemanager myresmgr;

Friend Class MyResmgr;

PUBLIC:

}

This will work on most compilers. But change to G - 4.0 will report an error. We must write a regulations:

Template Class HRESOURCE

{

Typedef resourcemanager myresmgr;

Friend Class ResourceManager ;

PUBLIC:

}

I really have enough metamorphosis .....!

2: Template derived class member variable

Template Class TBASE

{

protected:

INT m_size;

}

Template Class Tderived: Public TBASE

{

Void foo ()

{

m_size = 0; // The definition of the variable is not found in the G 4.0 report.

this-> m_size; // correct

TBASE :: m_size; // correct

}

}

3: Template derived static member variable problem

/*Singleton.h*/

Template Class Csingleton

{

protected:

Static t * ms_psingleton;

}

/*somefile.cpp*/

CsomeClass * csingleton :: ms_psingleton = null; // g - 4.0 Report Template Parameter Error

The correct way of writing is

/*somefile.cpp*/

Template <> csomeclass * csingleton :: ms_psingleton = null;

Or written like this /*singleton.h*/

/*Singleton.h*/

Template Class Csingleton

{

protected:

Static t * ms_psingleton;

}

Template t * csingleton :: ms_psingleton = null;

This is no longer written in the CPP file.

I recommend the previous way. But the latter is laborious.

These have been recently found, these are in C books. But it is easy to be ignored.

转载请注明原文地址:https://www.9cbs.com/read-131076.html

New Post(0)