brance
brance

Reputation: 1178

C++ 11 template Class create instance

This is a excerpt from my header file

template <typename E>
class Container {
public:
  Container& operator=(const Container&) = delete;
  Container(const Container&) = delete;
  Container() = default;

  virtual ~Container() { }
...

Then I've created another header file to declare a new class and to implement the methods (these are not shown now)

template <typename E>
class SepChaining : public Container<E> {
  size_t nmax;
  size_t n;
  int *values;
public:

  SepChaining<E>( size_t nmax ) : nmax(nmax), n(0), values( new int[this->nmax]) { }

  virtual ~SepChaining<E>( );

Here I've created a new class SepChaining that inherits the Container class and I created a constructor to assign the nmax and values

Now my question: How do I create a new instance of this class? I am really confused with where I need to specify the actual template value, say int

EDIT:

Header.h

 #include <iostream>
 #include <functional>

enum Order { dontcare, ascending, descending };

template <typename E>
class Container {
public:
  Container& operator=(const Container&) = delete;
  Container(const Container&) = delete;
  Container() = default;

  virtual ~Container() { }

  virtual void add(const E& e) { add(&e, 1); }
  virtual void add(const E e[], size_t s) = 0;

  virtual void remove(const E& e) { remove(&e, 1); }
  virtual void remove(const E e[], size_t s) = 0;

  virtual bool member(const E& e) const = 0;
};

SepChaining.h

 #include <iostream>
 #include "Container.h"

template <typename E>
class SepChaining : public Container<E> {
    size_t nmax;
    size_t n;
    int *values;
public:

    SepChaining<E> ( size_t nmax ) : nmax(nmax), n(0), values(new int[this->nmax]) { }

    virtual ~SepChaining ();

    using Container<E>::add;
    virtual void add(const E e[], size_t s);

    using Container<E>::remove;
    virtual void remove(const E e[], size_t s);

    virtual bool member(const E& e) const;

};

SepChaining.cpp

#include <iostream>
#include "SepChaining.h"

template <typename E>
SepChaining<E>::~SepChaining( ){
    delete[] values;
}

template <typename E>
void SepChaining<E>::add(const E e[], size_t s) {
    std::cout << "Add method";
}

template <typename E>
void SepChaining<E>::remove(const E e[], size_t s) {
    std::cout << "Remove method";
}

template <typename E>
bool SepChaining<E>::member(const E &e) const {
    for (size_t i = 0; i < n; ++i) {
        if (values[i] == e) return true;
    }
    return false;
}

So these are my three files, the main.cpp is just initialising of the constructor as you told me. I can't see any problem with my code..

Upvotes: 0

Views: 4851

Answers (1)

erenon
erenon

Reputation: 19118

Simply change E to int:

SepChaining<int> instance;

Upvotes: 1

Related Questions