Answer the question
In order to leave comments, you need to log in
Code splitting. Moving the implementation of the class template methods from the ".h" header file to the ".cpp" source file?
It is not possible to separate the code into a class template and into the implementation of the methods of the class template.
The class template is quite simple, it has a default constructor with a default argument (the argument specifies the number of elements in the array) and a destructor. The class implements a wrapper around a standard C array.
I do this:
main.cpp
#include <iostream>
#include <TypeArray.h>
int main(){
TypeArray<int> massive(5);
return 0;
}
#include <TypeArray.h>
template<typename Type>
TypeArray<Type>::TypeArray(int size){
_size = size;
pia = new Type[_size];
if( typeid(*pia).name() == typeid(char).name() ){
for(int i(0); i < _size; ++i){
pia[i] = '?';
}
}else{
for(int i(0); i < _size; ++i){
pia[i] = 0;
}
}
}
template<typename Type>
TypeArray<Type>::~TypeArray(){
delete[] pia;
}
#ifndef TYPEARRAY_H
#define TYPEARRAY_H
#include <iostream>
#include <typeinfo>
using namespace std;
template <typename Type>
class TypeArray{
private:
Type *pia;
int _size;
public:
//конструктор по умолчанию
TypeArray(int size = 10);
//Деструктор
~TypeArray();
};
#endif
Answer the question
In order to leave comments, you need to log in
You either explicitly instantiate the TypeArray in the implementation file, or put the constructor and destructor definitions back in the header file. How do you think the compiler knows with what parameters you instantiate this template in other files?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question