Template Class with Class Member

I don't have many experience with templates, but I'm trying to learn on the go, so could someone please tell me what do I do to make this work, because I have seen a lot of examples of using typenames and explicit instantion and explicit specialization but they just include the basic types like int,char,...
So please help because I don't understand what to do.

Container.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    #ifndef CONTAINER_H
    #define CONTAINER_H
    
    template <typename E>
    class Container
    {
        private:
            E element;
        public:
            Container(E pElement);
            virtual ~Container();
    
    };
    
    #endif // CONTAINER_H 

Container.cpp
1
2
3
4
5
6
7
8
9
10
    #include "Container.h"
    #include "Piece.h"
    
    template class Container<Piece>;
    
    template <typename E>
    Container<E>::Container(E pElement) //Error Here;
    {
        element=pElement;
    }

Piece.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    #ifndef PIECE_H
    #define PIECE_H
    
    #include <iostream>
    #include <string>
    using namespace std;
    
    class Piece
    {
        private:
            int x;
            int y;
            string z;
        public:
            Piece(int pX,int pY, string pZ);
            virtual ~Piece();
    
    };
    
    #endif // PIECE_H 

Piece.cpp
1
2
3
4
5
6
7
    #include "Piece.h"
    
    Piece::Piece(int pX, int pY, string pZ){
        x=pX;
        y=pY;
        z=pZ;
    }


And the error I'm getting is this:
1
2
3
4
5
6
    src\Container.cpp|7|error: no matching function for call to 'Piece::Piece()'|
    src\Container.cpp|7|note: candidates are:|
    src\Piece.cpp|3|note: Piece::Piece(int, int, std::string)|
    src\Piece.cpp|3|note:   candidate expects 3 arguments, 0 provided|
    include\Piece.h|8|note: Piece::Piece(const Piece&)|
    include\Piece.h|8|note: Piece::Piece(const Piece&)|

And I don't know what I'm supposed to do there to make things work.
There is no default constructor in piece without parameter either u can create one constructor in piece which is having no parameter or call explicitly the constructor as E element(x,y,string pz)
You need to fix up the assignment in the Container constructor to use an initialisation list and move the explicit declaration of the Piece specialisation so that it's after the constructor:

In Container.cpp...
1
2
3
4
5
6
7
8
template <typename E>
Container<E>::Container(Element pElement)
: element(pElement)
{

}

template class Container<Piece>;


When you create a specialised Piece instance of your container, you'd do so like this:
Container<Piece> myContainer(Piece(1, 2, "three"));
Last edited on
Topic archived. No new replies allowed.