簡體   English   中英

C++ CRTP派生類對象切片

[英]C++ CRTP derived class object slicing

我有基類 Account 和派生類 Student 和 Teacher。 我在 CRTP 中實現了讀/寫,這樣我就不需要在每個類中編寫函數。
奇怪的是,read函數中有對象切片,函數中使用了*this,而write函數中沒有。

誰能解釋這里發生了什么? 以及如何修復它?

// Account.h
class Account {
public:
    Account();
    virtual void callMenu() = 0;
protected:
    int ID;
    // Some more data (Total of 148 bytes)
}

// AccountCRTP.h
template<class T>
class AccountCRTP : public Account {
public:
    // To prevent object slicing
    void callMenu() {
        T account;
        account.ID = this->ID;
        cout << "Account size: " << sizeof(account) << " bytes\n"; pause(); // 268 bytes
        if (account.readData())
            account.menu();
    }

    bool readData() {
        T account;

        cout << "Account size : " << sizeof(account) << " bytes\n"; pause(); // 268 bytes
        cout << "This size    : " << sizeof(*this) << " bytes\n"; pause();   // 148 bytes??? Why?

        while (reading data to account) {
            if (this->ID == account.ID) {
                *this = account; // Object slicing happens
                return true;
            }
        }
        return false;
    }

    bool writeData() {
        T temp;
        int position = 0l
        while (reading data to temp) {
            if (this->ID == account.ID)
                break;
            position++;
        }

        cout << "Account size : " << sizeof(temp) << " bytes\n"; pause();  // 268 bytes
        cout << "This size    : " << sizeof(*this) << " bytes\n"; pause(); // 148 bytes right?

        datafile.seekp(position * sizeof(T));

        // For unknown reason this also writes scores of the student
        // Object slicing didn't happen here. Why?
        datafile.write((char*)this, sizeof(T)); 
    }
private:
    // No additional data in this class (Still 148 bytes)
}

// Student.h
class Student :
    public AccountCRTP<Student>
{
public:
    void menu() {
        // Student menu
    }

private:
    // Some more 120 bytes of data (Total of 268 bytes)
}


// main.cpp
int main() {
    vector<unique_ptr<Account>> account;
    account.push_back(unique_ptr<Account>(new Student));
    account.push_back(unique_ptr<Account>(new Teacher));

    account[0]->callMenu();
}
*this = account; // Object slicing happens

“對象切片發生”是的,您正在丟失account任何特定屬性(成員變量)

你真正需要的是

*static_cast<T*>(this) = account;

保留派生T


static_cast<T*>(this)技巧是使靜態多態起作用的類型安全的全部要點。
所有可能的類型檢查都將在編譯時應用。


讓我們在@Yakk 的評論中提到的更多語法糖

template<typename T>
struct CRTPBase {
    T const& self() const { return *static_cast<T const*>(this); } 
    T& self() { return *static_cast<T*>(this); } 
};

然后線變成

 self() = account;

對於這種情況,即使使用 c 預處理器宏似乎也是合適的:

#define DEFINE_CRTP_SELF(derived_param) \
     derived_param const& self() const { return *static_cast<derived_param const*>(this); } 
     derived_param& self() { return *static_cast<derived_param*>(this); } 

並像這樣使用它:

template<typename T>
class CRTP {
public:
    DEFINE_CRTP_SELF(T);
};

注意:如果你在運行時有一些奇怪的東西(來自void*指針左右),你就會迷失在地獄中。

暫無
暫無

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

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