簡體   English   中英

使用std :: unique_ptr使用CRTP進行投射

[英]up casting with CRTP using std::unique_ptr

我指的是並使用CRTP跟蹤所創建的對象的數量。 但我碰到編譯問題,當我嘗試了鑄ProfessorStudent classPerson class具有std::unique_ptr 請參考下面的代碼段,鏈接在這里

#include <iostream>
#include <vector>
#include <memory>
#include <numeric>
#include <exception>

using namespace std;

template<typename T>
class Person
{
    public:
    Person(string Name="", int Age=0) : name(Name), age(Age) 
    {
        ++cur_id;
    }
    virtual ~Person() {}
    virtual void getdata() = 0;
    virtual void putdata() = 0;

    protected:
    string name;
    int age;
    static int cur_id;
};

template<typename T> int Person<T>::cur_id = 0;

class Professor : public Person<Professor>
{
    public:
    Professor(string Name="", int Age=0, int Publications=0);
    ~Professor() {}
    void getdata() override;
    void putdata() override;

    protected:
    bool IsValidInput();

    private:
    int publications;
};

Professor::Professor(string Name, int Age, int Publications) try : Person(Name,Age), publications(Publications)
{
}

// Catch constructor that fails
catch(std::exception & e)
{
    std::cout<<"\n Exception - "<<e.what()<<std::endl;
    exit(1);    
}

bool Professor::IsValidInput()
{
    if (name.empty() || (name.length() > 100))
    {
        return false;
    }

    if ( age <= 0 || age > 80 )
    {
        return false;  
    }

    if ( publications <= 0 || publications > 1000)
    {
        return false;
    }

    return true;
}

void Professor::getdata()
{
    cout<< "Enter Name age publications" << endl;
    cin >> name >> age >> publications;

    if (!IsValidInput())
    {
        throw std::invalid_argument("wrong arguments");
    }
}

void Professor::putdata()
{
    cout << name << " " << age << " " << publications << " " << cur_id << endl;
}

class Student : public Person<Student>
{
    public:
    Student(string Name="", int Age=0, const vector<int> & Marks = vector<int>());
    ~Student() {}

    void getdata() override;
    void putdata() override;

    protected:
    bool IsValidInput();    

    private:
    vector<int> marks;
    static const int TOTAL_MARKS = 5;
};

Student::Student(string Name, int Age, const vector<int> & Marks) try : Person(Name,Age), marks(Marks)
{
}

// Catch constructor that fails
catch(std::exception & e)
{
    std::cout<<"\n Exception - "<<e.what()<<std::endl;
    exit(1);    
}

void Student::getdata()
{
    int mark = 0;
    cout<< "Enter Name age marks(5)" << endl;
    cin >> name >> age;

    for (size_t idx = 0; idx < TOTAL_MARKS; ++idx)
    {
        cin >> mark;
        marks.push_back(mark);
    }

    if (!IsValidInput())
    {
        throw std::invalid_argument("wrong arguments");
    }
}

void Student::putdata()
{
    cout << name << " " << age << " " << std::accumulate(marks.begin(),marks.end(),0) << " " << cur_id << endl;
}

bool Student::IsValidInput()
{
    if (name.empty() || (name.length() > 100))
    {
        return false;
    }

    if ( age <= 0 || age > 80 )
    {
        return false;  
    }

    for (size_t idx = 0; idx < marks.size(); ++idx)
    {    
        if ( marks[idx] < 0 || marks[idx] > 100 )
        {
            return false;
        }
    }
    return true;
}

int main()
{
    int totalObj = 0, type = 0;
    cout<< "Enter total obj : ";
    cin >> totalObj;

    std::vector<std::unique_ptr<Person<int>>> person;

    for (int idx = 0; idx < totalObj; ++idx)
    {
        cout<< "Enter obj type (1 or 2) : ";
        cin >> type;

        switch(type)
        {
            case 1:
            {
                std::unique_ptr<Person<int>> temp(std::make_unique<Professor>());
                temp->getdata();
                person.push_back(std::move(temp));
            }
            break;

            case 2:
            {
                std::unique_ptr<Person<int>> temp(std::make_unique<Student>());
                temp->getdata();
                person.push_back(std::move(temp));
            }
            break;

            default:
            break;
        }
    }

    for (auto itr = person.begin(); itr != person.end(); ++itr)
    {
        (*itr)->putdata();
    }

    return 0;
}

問題出在switch case 1 and 2 我只是使用int實例化class Person 當我編譯它時,出現以下錯誤

      In function 'int main()':
181:80: error: no matching function for call to 'std::unique_ptr<Person<int> >::unique_ptr(std::_MakeUniq<Professor>::__single_object)'
181:80: note: candidates are:
In file included from /usr/include/c++/4.9/memory:81:0,
                 from 3:
/usr/include/c++/4.9/bits/unique_ptr.h:228:2: note: template<class _Up, class> std::unique_ptr<_Tp, _Dp>::unique_ptr(std::auto_ptr<_Up>&&)
  unique_ptr(auto_ptr<_Up>&& __u) noexcept;
  ^
/usr/include/c++/4.9/bits/unique_ptr.h:228:2: note:   template argument deduction/substitution failed:
181:80: note:   'std::_MakeUniq<Professor>::__single_object {aka std::unique_ptr<Professor, std::default_delete<Professor> >}' is not derived from 'std::auto_ptr<_Up>'
In file included from /usr/include/c++/4.9/memory:81:0,
                 from 3:

請提出如何將Professor and StudentPerson std::unique_ptr

您的問題是StudentProfessor沒有擴展Person<int> 實際上, Person<int>Professor無關,每個Person<...>都是完全不同的類,彼此之間沒有關系。

如果要將所有人員類型保留在向量中,則需要一個多態類,該類在所有Person<...>上提供一個接口。

您的問題的解決方案是創建一個抽象的人:

struct AbstractPerson {
    virtual void getdata() = 0;
    virtual void putdata() = 0;
    virtual ~AbstractPerson() = default;
};

然后,使Person<T>從該類繼承:

template<typename T>
struct Person : AbstractPerson {
    // ...
};

然后,將不相關的std::vector<Person<int>>替換為:

std::vector<std::unique_ptr<AbstractPerson>> person;

// ...

person.emplace_back(std::make_unique<Student>()); // works!

這是您工作的實時版本,代碼略有現代化: 在Coliru上實時運行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM