[英]How can I pass both `int` and `unsigned int` members, by reference or pointer, to the same function?
我有一個20-30行的C ++函數,該函數正在引用一個int
以進行可能的更新。 現在,我將封裝了更多數據的成員替換為傳遞給它的成員,例如:
searchState.matchedOK = specificSearch(*pageIndices.GetStringIByRef(), searchState); //new, and overwritten.
searchState.matchedOK = specificSearch(pageOffsetInText, searchState); //old
我想將此修改本地化為上面調用的行和函數,因為一旦我驗證了等效性及以后的功能,就應刪除舊成員。
簡單的轉換有可能嗎?
如果您需要代碼:
static bool specificSearch(int &matchLocation, const SearchSpecs &specs) {/**/}
和最近添加的成員:
inline unsigned int *GetStringIByRef() {return &stringI;}
我不確定100%理解您的問題,因此我可能會完全錯過這里的記號。 但是,如果您將函數設為模板:
template<typename IntType>
static bool specificSearch(IntType &matchLocation, const SearchSpecs &specs) {/**/}
這樣您就可以將任何一種類型傳遞給它。
您的基本問題是您的函數specificSearch
分配給一個int
對象。 但是您要編寫的東西是一個unsigned int
對象。 幸運的是,嚴格的別名規則使我們能夠像寫unsigned int
一樣寫入unsigned int
int
。 類型系統並不完全鼓勵它,但是可以被說服:
searchState.matchedOK = specificSearch(*reinterpret_cast<int*>(pageIndices.GetStringIByRef()), searchState);
這種排序取決於要寫入的值處於兩種類型(0到INT_MAX
)的公共范圍內。 我之所以說“ sort of”,是因為在2的補碼系統中,寫入超出該范圍的值的結果與將值轉換為unsigned int
的結果相同。 在實際上不存在但原則上困擾我們嘗試可移植代碼的非2's補碼系統上,結果是不同的,因此可能是錯誤的。
如果可能的話,定義specificSearch
的重載可能會更好:
static bool specificSearch(unsigned int &matchLocation, const SearchSpecs &specs) {
int loc;
bool retval = specificSearch(loc, specs);
if (retval) { // I'm guessing here about the meaning of the return value
matchLocation = loc; // converts int to unsigned int
}
return retval;
}
假設包裝函數可以告訴“真正的” specificSearch
分配給loc
,從而知道是否分配給matchLocation
。 如果調用函數無法以某種方式弄清楚這一點,那么這實際上是行不通的(並且如果允許specificSearch
分配然后拋出異常,那么您也需要考慮這一點)。
如果可能的話,將stringI
更改為正確的類型會更明智。
您可以使用模板執行此操作:
template<typename T>
static bool specificSearch(T& matchLocation, const SearchSpecs& specs) {/**/}
並在函數內部分配給matchLocation
。 這樣,您可以使用可以分配給函數中的matchLocation
任何類型。
如果由於某種原因您不喜歡它,並且希望它僅與int
和unsigned int
使用,則可以使用模板專門化:
// leaving this undefined, which will cause a linker error if you use it with other types
template<typename T>
static bool specificSearch(T& matchLocation, const SearchSpecs& specs);
template<>
static bool specificSearch<int>(int& matchLocation, const SearchSpecs& specs) {
/* definition */
}
template<>
static bool specificSearch<unsigned int>(unsigned int& matchLocation, const SearchSpecs& specs) {
// use the other one to avoid code duplication
int tmp = matchLocation;
bool retval = specificSearch(tmp, specs);
matchLocation = tmp;
return retval;
}
注意,使用這兩個函數可能會在int
和unsigned int
之間進行轉換時發出警告,因為兩種類型的范圍是不同的。
我在這里看到幾個問題。 首先,根據您的意圖,最好僅按值返回stringI
。 否則,您可以如下調整其簽名:
inline unsigned int &GetStringIByRef() { return stringI; }
為了利用C ++引用。
至於
static bool specificSearch(int &matchLocation, const SearchSpecs &specs) {/**/}
您可以按如下調用它,則 :
searchState.matchedOK = specificSearch(reinterpret_cast<unsigned int&>(pageIndices.GetStringIByRef()), searchState);
我認為仍然取決於對象本身(如果是const
)。
如果有任何不清楚的地方或我錯過了要點,請發表評論,然后我將調整答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.