[英]How to pass std::vector<void*> * as std::vector<MyStruct*>* to a function
如何將std::vector<void*> *
作為std::vector<MyStruct*>*
傳遞給函數?
函數聲明為void SetDataReferences(std::vector<MyStruct*>* pVector);
如果我通過std::vector<void*> *
作為std::vector<MyStruct*>*
我遇到了以下錯誤
錯誤C2664:'CTagFilterComboBox :: SetDataReferences':無法將參數2從' std::vector<_Ty> *
'轉換為' std::vector<_Ty> *
'
如何解決呢?
不幸的是std::vector<void*>
是與std::vector<MyStruct*>*
完全不同的類型,因此沒有std::vector<MyStruct*>*
轉換。
您需要從頭開始重建向量,並將指向該向量的指針傳遞給您的函數,並希望每個元素上的static_cast
有效。
給定std::vector<void*>* foo
;
std::vector<MyStruct*> temp;
for (void* p : *foo){
temp.push_back(static_cast<MyStruct*>(p));
}
如果不需要修改vector<void*> foo
則可以通過將函數簽名更改為以下內容來處理基礎數據: void SetDataReferences(MyStruct*const* pVector, const size_t length)
(請記住const
為左關聯,因此這是指向MyStructs的常量指針。)可以這樣稱為:
SetDataReferences(reinterpret_cast<MyStruct*const*>(data(foo)), size(foo))
如果您需要修改vector<void*> foo
的元素(而不是大小),您仍然可以將函數簽名更改為: void SetDataReferences(MyStruct** pVector, const size_t length)
這可以稱為:
SetDataReferences(reinterpret_cast<int**>(data(foo)), size(foo))
如果需要修改更復雜的vector<void*> foo
,則需要接受vector<void*>
就像函數簽名在問題中所做的那樣,並在使用時而不是在組中強制轉換元素。
我從此鏈接https://www.codeproject.com/Questions/1261243/How-to-pass-std-vector-void-as-std-vector-mystruct獲得了解決問題的方法,它對我有用。
如果我調用SetDataReferences((std::vector<MyStruct*>*)(&p1))
它將為我工作,而不會出現任何編譯器錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.