Templates and Class in C++

Hello,

I have found 2 exercices on internet and I don’t understand to solve it, there are the exercices :

  1. Code a class “SmartPointer”, it should be able to be used as a pointer. When the class instance is destroyed, the pointer is destroyed as well. The use of “void *” is forbidden, The class will have to support any type pointer.

  2. Code a function “print” which displays the number of parameter of the function then show them one by one.

Thanks you for your help :slight_smile:

Hi @elden97,

This post was moved to a different board that fits your topic of discussion a bit better. This means you’ll get better engagement on your post, and it keeps our Community organized so users can more easily find information.

As you’ll notice, your Topic is now in the Project Development Help and Advice board. No action is needed on your part; you can continue the conversation as normal here.

Let me know if you have any other questions or if I can help with anything else.

Cheers!

The first exercise can be approached using templates.

Templates in C++ are great. Without templates, you might have to define your smart pointer as follows:

typedef enum SmartPointerTypes {

	INTEGER

} SmartPointerType;

typedef void * ForbiddenSmartPointer;

void useAndDelete(ForbiddenSmartPointer ptr,SmartPointerType type ) {

    if(type==INTEGER) {
         int * intPointer = (int*)ptr;

         int value = intPointer;
delete intPointer;
}

}

To write the same code using a template would look as follows:

template <typename Type> void useAndDelete(Type * ptr) {
	Type value = *ptr;
	delete ptr;
}

The second exercise could be asking you to use templates with more than one parameter, or it could be trying to introduce variadic functions