简体   繁体   English

如何在代码中识别const char *和const char []的类型?

[英]How to identify the type of const char* and const char[] in code?

const char* s1   = "teststirg";  
const char  s2[] = "teststirg";

I want a method tell me that s1 is "char*" and s2 is "char[]",how to write the method? 我想要一个方法告诉我s1是“ char *”而s2是“ char []”,如何编写该方法?

Use templates: 使用模板:

template<typename T, unsigned int SIZE>
bool IsArray (T (&a)[SIZE]) { return true; }

template<typename T>
bool IsArray (T *p) { return false; }

This will evaluate at runtime. 这将在运行时评估。
Usage: 用法:

if(IsArray(s1))
...

if(IsArray(s2))
...

If interested, you can use some advance techniques, which will tell you this as compile time. 如果有兴趣,您可以使用一些高级技巧,这些技巧将在编译时告诉您。

Edit : 编辑

typedef char (&yes)[2];

template<typename T, unsigned int SIZE>
yes IsArray (T (&a)[SIZE]);

template<typename T>
char IsArray (T *p);

Usage: 用法:

if(sizeof(IsArray(s1)) == sizeof(yes))
...
if(sizeof(IsArray(s2)) == sizeof(yes))
...

If you have access to the original definition, then typeid can be used (but what for, I don't know). 如果您有权访问原始定义,则可以使用typeid (但是我不知道该做什么)。 If you don't have access to the original definition... There's no way of knowing whether a char* was initialized from another char* , or from an array. 如果您无权访问原始定义,则无法知道char*是从另一个char*还是从数组初始化的。

In the above context ( that is in the same method where we have the declaration), 在上述情况下(即使用声明的相同方法),

   /*1*/ s1[0]='\0';
   /*2*/ s2=s1;
   /*3 Only This is valid*/  s1=s2;
   /*4*/  s2[0]='\0';

Your compiler wouldn't allow step 1,2,4 to pass, while step 3 would succeed. 您的编译器不允许步骤1,2,4通过,而步骤3将成功。 This clearly indicates the nature of the variables. 这清楚地表明了变量的性质。 Now, as regards the method (function call) to determine that, you will have to have the definition in the method signature anyways, so I dont see any purpose/utility/possiblity of this method. 现在,关于确定方法(函数调用),无论如何,您都必须在方法签名中具有定义,因此我看不到该方法的任何用途/用途/可能性。

determiner (const char* s1,const char *const s2)

You already have the definition in the signature.You need to bypass compiler, to get a use case for this. 签名中已经有了定义。您需要绕过编译器,以获取用例。 I apologise , If I haven't got your requirement correct. 抱歉,如果我对您的要求不正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM