T
T
Timur Tokar2014-11-19 19:37:55
C++ / C#
Timur Tokar, 2014-11-19 19:37:55

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;
}

TypeArray.cpp
#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;
}

TypeArray.h
#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

The compiler complains about:
339f758a79f14c90ad2e4cbfd3790595.jpeg

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2014-11-19
@jcmvbkbc

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?

S
SHVV, 2014-11-20
@SHVV

For the implementation of templates, we have introduced a special extension of the ".tpl" type, where the implementation is described. This file is included right at the end of the header file to avoid double includes at the point of use.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question