Hi
I came accross a code and i din't understand it


Template.h

#define FRIEND_NEW template<class T> friend inline T* ::safe_new(const char*,int);

template<typename T> inline T* safe_new0(const char* file, int line)
{
 T* ptr = new T();

 return ptr;
};

A.h

#include "Template.h"
class A
{
  FRIEND_NEW
protected:

	A();
};

What is this template code?
As I went thorough the multiple classes of the project I got to know that this guy trying to keep protected constructors and create instances in the fiend classes.

But this template structure I am not clear.
Can you please explain?

Recommended Answers

All 3 Replies

Are you asking what templates are? Or what is the job of template in your code? If you don't know what templates are, before trying to understand this code, you need to learn about templates. Take a good book or take some online material about templates and learn.

I will brief about template functions here

template <class T>
T GetMax (T a, T b) {
  T result;
  result = (a>b)? a : b;
  return (result);
}

Here we have a GetMax function which accepts two arguments, both of type T and returns T type. The functionality inside this function is generic for all data types. Why a template is used is because you don't need to repeat the code for each and every data type like int, double, char etc.
But you have to note that the duplication is avoided only in the source code. When this code is compiled, the compiler generates separate versions of this function for separate data types, by replacing the T with int or double or char or any other. Now, how many versions of this function is to be generated? It is determined by the number of function calls to the template function. Suppose the following lines are there in your code

GetMax(4, 7);
GetMax(3.45, 8.10);
GetMax(8.121, -902.12);

Here two versions of the GetMax will be generated.

int GetMax(int, int);
double GetMax(double, double);

This was just a brief overview. There are more to read about templates. Also, go through template classes and read about template instantiation. After some basic reading, this link will help you understand more.

Thank you very much for explanation,

Actually what this line does is what I am not clear

#define FRIEND_NEW template<class T> friend inline T* ::safe_new(const char*,int);

That is just a macro that expands in your code snippet

class A
{
  FRIEND_NEW
protected:

	A();
};

to

class A
{
  template<class T> friend inline T* ::safe_new(const char*,int);
protected:

	A();
};
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.