lundi 27 janvier 2020

Creation of template class objects

I made this template class:

//Elenco.h

#pragma once
#include "Tipi.h"
#include <vector>

template <typename T>
class Elenco
{
public:
    //constructor
    Elenco() : Elenco::Elenco(std::vector<T> {})
    { }

    Elenco(const std::vector<T>& _list) : list{ _list }
    {
        sort();
    }

    //setter
    T add(const T&);

    //viewer
    const std::vector<T>& view() const;

private:
    std::vector<T> list;

    void sort();
};

//Elenco.cpp

#include "Elenco.h"
#include <algorithm>
#include <iostream>

//setter
template<typename T>
T Elenco<T>::add(const T& item)
{
    list.push_back(item);

    sort();
}


//viewer
template<typename T>
const std::vector<T>& Elenco<T>::view() const
{
    return list;
}


//private
template<typename T>
void Elenco<T>::sort()
{
    for (unsigned short n = 0; n < list.size(); n++)
        for (unsigned short m = 0; m < n; m++)
        {
            std::cout << list[m] << "-" << list[n] << ": " << bool(list[m] > list[n]) << std::endl;
            if (list[m] < list[n]) std::swap(list[m], list[n]);
        }
}

The problem is that when I try to create an object I get these errors:

unresolved external symbol "public: class std::vector > const & __thiscall Elenco::view(void)const " (?view@?$Elenco@VGiocatore@@@@QBEABV?$vector@VGiocatore@@V?$allocator@VGiocatore@@@std@@@std@@XZ) referenced in function _main


unresolved external symbol "private: void __thiscall Elenco::sort(void)" (?sort@?$Elenco@VGiocatore@@@@AAEXXZ) referenced in function "public: __thiscall Elenco::Elenco(class std::vector > const &)" (??0?$Elenco@VGiocatore@@@@QAE@ABV?$vector@VGiocatore@@V?$allocator@VGiocatore@@@std@@@std@@@Z)


2 unresolved externals

I found in another post that you can fix this by including Elenco.cpp in my main.cpp file, or by including it at bottom of Elenco.h excluding the file from the project.

Both solutions work, but they doesn't seem great because I lose the main purpose of an header: allowing to modify my definition without re-compiling my projects...

So I could I fix that? And (above all) why do I get there errors?

Aucun commentaire:

Enregistrer un commentaire