我们可以创建一个 IF 语句来确定变量是否已在 C/C 中声明为指针吗?
假设变量 pa
始终声明为以下两种方式之一:
双 * pa
或
双屏
我们可以创建一个执行以下操作的 IF 语句吗
IF(pa是指针) { 帕[0] = 1 }
其他 { pa = 1}
编辑:
请参阅 如何在C++/C中查找指针数组是否已被填充作为后续问题
Suppose a variable pa
is always declared as one of two ways:
double * pa
OR
double pa
Can we create an IF statement that does the following
IF (pa is a pointer)
{ pa[0] = 1
}ELSE
{ pa = 1}
EDIT:
Please see How to find out if a pointer array has been filled in C++/C for the follow up question
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
C++0x
std::is_pointer
工作原理的基础知识:对于此示例,我们不想使用该类型,因此我们需要一些模板参数推导:
我们就完成了:
但是,请注意,除非
pa[0] = 1
和pa = 1
都是有效表达式(并且对于double< /code> 也不是
double*
它们都有效吗?如果您设置为0
,那么两者都对double*
有效,但对于double
仍然只有第二个有效)。因此,您可能想要的不是显式的“if”测试,而是重载函数:或者,因为
pa
始终是double
或double*
,没有必要关注一个是指针而另一个不是的事实,它们只是我们需要区别对待的两种不同类型。所以不需要模板:The basics of how C++0x
std::is_pointer
might work:For this example we don't want to have to use the type, so we need some template argument deduction:
And we're done:
BUT, note that this code still won't compile unless
pa[0] = 1
andpa = 1
are both valid expressions (and for neitherdouble
nordouble*
are they both valid - if you were setting to0
then both would be valid fordouble*
, but still only the second fordouble
). So probably what you want is not an explicit "if" test, but an overloaded function:Or, since
pa
is alwaysdouble
ordouble*
, there's no need to focus on the fact that one is a pointer and the other is not, they're just two different types that we need to treat differently. So no need for templates:不直接,不。假设有一种方法可以做到这一点,例如
如果 pa 不是指针会发生什么?您的程序中仍然有
pa[0] = 1;
语句,并且它是非法的,因此编译器将拒绝您的程序。原则上您也许能够进行编译时测试:
但是 C++ 预处理器的功能非常有限;它无法测试变量或表达式的类型。
如果你有这个能力,你会用它做什么?告诉我们您的实际目标是什么。
Not directly, no. Suppose there were a way to do this, something like
What happens if pa isn't a pointer? You still have that
pa[0] = 1;
statement in your program, and it's illegal, so the compiler is going to reject your program.You might in principle be able to do a compile-time test:
but the power of the C++ preprocessor is very limited; it has no way to test the type of a variable or expression.
If you had this capability, what would you do with it? Tell us what your actual goal is.
在 C++0x 中,您可以使用类型特征和
decltype
:在 C++98/03 中,您没有
decltype
,但现在您必须解释你怎么可能在不知道变量类型的情况下拥有它。如果你确实有它的类型,你可以使用相同的类型特征:如果你没有或不想使用 TR1,你也可以定义自己的特征类:
In C++0x you can, using type traits and
decltype
:In C++98/03 you don't have
decltype
, but now you'd have to explain how you could possibly have a variable without knowing its type. If you do have its type, you can use the same type trait:You can also just define your own trait class if you don't have or want to use TR1: