[英]Casting const void * to const char *
Doing a sort function exercise for pointers to functions, so I'm writing a comparison function for char*
.对指向函数的指针进行排序 function 练习,所以我正在为char*
编写比较 function 。
cmp2(const void *p, const void *q)
How do I convert the void *p
to char*
?如何将void *p
转换为char*
?
I tried const char* cp = static_cast<const char *>(p);
我试过const char* cp = static_cast<const char *>(p);
but it doesn't work...但它不起作用......
I don't want to use C-style casting like (const char *)p
or something like that我不想使用像(const char *)p
这样的 C 风格转换或类似的东西
static_cast<const char *>
should work fine! static_cast<const char *>
应该可以正常工作!
The following code snippet demonstrates it.下面的代码片段演示了它。
#include <iostream>
bool compare(const void *p, const void *q){
const char * casted_p = static_cast<const char*>(p);
const char * casted_q = static_cast<const char*>(q);
return *casted_p == *casted_q;
}
int main(int argc, char * argv[]) {
char c1 = '6';
char c2 = '6';
const char *p1, *p2;
p1 = &c1;
p2 = &c2;
if(compare(p1,p2)){
std::cout << "equal" << std::endl;
} else {
std::cout << "diff" << std::endl;
}
return 0;
}
This will print equal
.这将打印equal
。
If one character is changed to something else, eg 7, it will print diff
.如果将一个字符更改为其他字符,例如 7,它将打印diff
。
I am not sure what would be the purpose of such a function, but it can be done!我不确定这样一个 function 的目的是什么,但可以做到!
Note: If what you are up to is type erasure, consider templates.注意:如果您要做的是类型擦除,请考虑使用模板。 It is safer and more modern approach.这是更安全、更现代的方法。 Using void *
for such a purpose is still C-style.为这样的目的使用void *
仍然是 C 风格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.