Reputation: 55
I am having troubles instantiating an object of a template class type in C++.
Here is the code:
Array.h:
//Developed by Trofimov Yaroslav on 30.03.2018
#ifndef _ARRAY_H_TROFIMOV_
#define _ARRAY_H_TROFIMOV_
template<size_t n, typename T>
class Array
{
static unsigned __freeId, __quantity;
unsigned _id;
T* _array;
public:
template<size_t n, typename T>
Array(void);
~Array(void);
T& operator[](const size_t);
};
#include "Array.cpp"
#endif
Array.cpp:
//Developed by Trofimov Yaroslav on 30.03.2018
#include "Array.h"
template<size_t n, typename T>
Array::Array(void)
: _id(++__freeId), _array(new T[]) {
}
template<size_t n, typename T>
Array::~Array(void) {
}
template<size_t n, typename T>
T& Array::operator[](const size_t i) {
}
Main.cpp:
//Developed by Trofimov Yaroslav on 30.03.2018
#include <iostream>
#include "Array.h"
int main(void) {
Array<7, int> a;
return 0;
}
Now when I hover over a
in Main.cpp
I see the following:
Error: no default constructor exists for class "Array<7U, int>"
But as you can see, the default template constructor does exist. So, what am I missing here?
Upvotes: 1
Views: 6093
Reputation: 595402
There are multiple errors in your code.
In your header file, you need to remove the extra template
from the constructor, it doesn't belong there.
In your cpp file, you need to replace all of the Array::
with Array<n, T>::
. Your constructor needs to pass n
to new[]
. Your destructor needs to delete[]
the array. And operator[]
needs to return something.
Your class has static
members, so you need to instantiate instances of them as well.
Try this:
Array.h
#ifndef _ARRAY_H_TROFIMOV_
#define _ARRAY_H_TROFIMOV_
template<size_t n, typename T>
class Array
{
static unsigned __freeId, __quantity;
unsigned _id;
T* _array;
public:
Array(void);
~Array(void);
T& operator[](const size_t);
};
#include "Array.cpp"
#endif
Array.cpp
#include "Array.h"
template<size_t n, typename T>
Array<n, T>::Array(void)
: _id(++__freeId), _array(new T[n]) {
}
template<size_t n, typename T>
Array<n, T>::~Array(void) {
delete[] _array;
}
template<size_t n, typename T>
T& Array<n, T>::operator[](const size_t i) {
return _array[i];
}
Main.cpp
#include "Array.h"
template<> unsigned Array<7, int>::__freeId = 0;
template<> unsigned Array<7, int>::__quantity = 0;
int main() {
Array<7, int> a;
return 0;
}
Upvotes: 1
Reputation: 36379
You don't need to use template when declaring methods or constructors inside your class. The constructor you've declared is a templated method inside a templated class rather than a default constructor.
I'd never rely on errors from intellisense, sometimes it's plain wrong, running the compiler will generally produce more accurate more detailed error messages.
Upvotes: 1