0

Hello I have created a template

Below is the header file:

#pragma once
#include <iostream>
using namespace std;

template <class T>
class Airplane {
private: 
    T model;
    int counter; 
public:
    Airplane(T model);
};

.cpp file:

#include "pch.h"
#include "Airplane.h"
#include <string>

template <class T>
Airplane<T>::Airplane(T model) {
    if (&model != NULL)
        this->model = model;
        this->counter = 1;
}

Then created a set template that can accept any data type or my created template Airplane but the set must contain unique objects.

set header file:

#pragma once
#include <vector>
#include <iostream>
using namespace std;

template <class T>
class set {
private:
    vector <T> setvector;
public:
    set();
    void insert(T obj);
};

set .cpp file:

#include "pch.h"
#include "set.h"
#include <iterator>

template <class T>
set<T>::set() {

    class vector<T>::iterator vi = this->setvector.begin();
}

template <class T>
void set<T>::insert(T obj) {    
    if (this->setvector.empty()) {
        this->setvector.push_back(obj);
    }
    else {
        class vector<T>::iterator vi = this->setvector.begin(); 
        bool flag = false;
        while (vi != this->setvector.end()) {
            if (*vi == obj) {
                flag = true;
                break;
            }
            vi++;
        }
        if (flag == false)
            this->setvector.push_back(obj);
    }

in the main method when i tried to use the set using int or doulbe it works perfectly, however when i try to instantiate a new set using my template "Airplane", VS throw Error

C3203   'Airplane': unspecialized class template can't be used as a template argument for template parameter 'T', expected a real type.

I have tried to create a specialization for my template but still c++ will not accept it since it seems like it is a template. I have tried using template <template <class> class T> in the set template but still did not work.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
AlexAlexis
  • 11
  • 2

1 Answers1

0

1) You should not use

  using namespace std;

in header files.

2) Templates should be defined in header files, not in cpp files. You may read about it here

3) Your issue, it seems you try to call

  set<Airplane> s;

set is a class template which takes some type. Your code works for int and double because they are types. Airplane is not a type. It is template, you can get type from template by instantiating it, so you need to provide one argument in template arguments list (<>) for Airplane.

  Airplane<int>

For instance, if you want to have set of Airplane<int> objects, write:

  set< Airplane<int> > mySet;

In addition, you have to add operator== for comparing Airplanes objects. Without it you will get errors in this line if (*vi == obj) { in insert method.

rafix07
  • 20,001
  • 3
  • 20
  • 33