如何将显式__FILE__强制转换为已签名的char *? [英] How to cast explicit __FILE__ to signed char*?

查看:176
本文介绍了如何将显式__FILE__强制转换为已签名的char *?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我有个问题.我必须将__FILE__强制转换为已签名的char *.
我有一个函数调用:

函数(par1,par2,__ FILE__)

__FILE__被声明为const char *,但是我需要显式强制转换,以将__FILE__转换为带符号的char *,而没有变量.

Hello,

I have a problem. I have to cast explicitly __FILE__ to signed char*.
I have a function call:

function(par1, par2, __FILE__)

__FILE__ is declared as const char*, but I need an explicit cast to convert __FILE__ to signed char* without a variable.

How can I do this?

推荐答案

这里有两个问题:const vs non-const和char * vssigned char *.

__FILE__不是变量,它是字符串文字的符号常量.尝试在运行时更改char *指向的内容是错误的,不应执行.

如果function()可能会更改其第三个参数所指向的内容,那么唯一的替代选择是不要在此处使用function()或创建缓冲区变量并将字符串复制到该变量.

如果保证function()在现在或将来重新实现时不做这样的更改,则应对其"进行修改,以使它的第三个参数是指向const的指针.如果无法做到这一点,则必须放弃常量.为此的C ++样式强制转换为const_cast<>(),尽管它本身不会处理将char签名的部分内容的char.
现在,有些出乎意料的是,普通字符,带符号的字符和无符号的字符在官方上并不像您期望的那样相关.它们之间的强制转换的含义是未指定",并且可能取决于实现/平台. (我需要自己弄清楚这一点.)为此,C ++ static_cast<>()是不合法的.

如果满足可以执行此操作的条件,则可以选择:

There are two issues here: const versus non-const and char * versus signed char *.

__FILE__ is not a variable, it is a symbolic constant for a string literal. Trying to change what the char * points to at runtime is an error and should not be done.

If function() might change what is pointed to by its third parameter, then your only real alternatives are to not use function() here or to create a buffer variable and copy the string to it.

If function() is guaranteed to not make such a change - now or in a future reimplementation - than it "should" be revised so that its third parameter is a pointer to const. If this is not possible, you will have to cast away the constness. The C++-style cast for this is const_cast<>(), though by itself it will not deal with the char to signed char part of things.

Now, somewhat surprisingly, plain char, signed char, and unsigned char are officially not as related as you might expect. The meaning of casting between them is "unspecified" and can be implementation/platform dependent. (I need to figure this out better myself.) A C++ static_cast<>() is not legal for this.

If you meet the conditions where you can do this, your options are:

(signed char*)__FILE__





or

reinterpret_cast<signed char*>( const_cast<char *>( __FILE__ ) )


我不确定我为什么会这样理解,但是应该可以:
I''m not sure I understand the whys and wherefores but this should work:
function(par1, par2, (signed char*)__FILE__);


这篇关于如何将显式__FILE__强制转换为已签名的char *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆