[英]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.