如何判断一个变量是指针

1、面试问题

编写程序判断—个变量是不是指针。

2、指针的判别

拾遗

C++中仍然支持C语言中的可变参数函数

C++编译器的匹配调用优先级

  1. 重载函数

  2. 函数模板

  3. 变参函数

思路

将变量分为两类:指针 vs 非指针

编写函数:指针变量调用时返回true ,非指针变量调用时返回false

函数模板与变参函数的化学反应

template  
<typename T>  
bool IsPtr(T* v) // match pointer  
{  
    return true;  
}  
  
bool IsPtr(...)  // match non-pointer  
{  
    return false;  
}

编程实验

指针判断 test.cpp

#include <iostream>

using namespace std;

class Test
{
public:
    Test()
    {
    }
    virtual ~Test()
    {
    }
};

template
<typename T>
bool IsPtr(T* v) // match pointer
{
    return true;}


bool IsPtr(...) // match non-pointer

{

return false;

}





int main(int argc, char argv[])

{

int i = 0;

int
p = &i;



cout << "p is a pointer: " << IsPtr(p) << endl; // 1

cout << "i is a pointer: " << IsPtr(i) << endl; // 0



Test t;

Test pt = &t;



cout << "pt is a pointer: " << IsPtr(pt) << endl; // 1



/


error: cannot pass object of non-trivial type 'Test' through variadic function; call will abort at runtime

/

cout << "t is a pointer: " << IsPtr(t) << endl; // 0 或 程序崩溃



return 0;

}

存在的缺陷: 变参函数无法解析对象参数,可能造成程序崩溃!

进—步的挑战: 如何让编译器精确匹配函数,但不进行实际的调用?

完美解决方案:

#include <iostream>  
  
using namespace std;  
  
class Test  
{  
public:  
    Test()  
    {  
    }  
    virtual ~Test()  
    {  
    }  
};  
  
template  
<typename T>  
char IsPtr(T* v) // match pointer  
{  
    return 'd';  
}  
  
int IsPtr(...)  // match non-pointer  
{  
    return 0;  
}  
  
#define ISPTR(p) (sizeof(IsPtr(p)) == sizeof(char)) // 通过使用sizeof在编译期间就能确定ISPTR(p)的值
  
int main(int argc, char *argv[])  
{  
    int i = 0;  
    int* p = &i;  
      
    cout << "p is a pointer: " << ISPTR(p) << endl;    // true  
    cout << "i is a pointer: " << ISPTR(i) << endl;    // false  
      
    Test t;  
    Test* pt = &t;  
      
    cout << "pt is a pointer: " << ISPTR(pt) << endl;    // true  
    cout << "t is a pointer: " << ISPTR(t) << endl;    // false  
      
    return 0;  
}

3、小结

C++中依然支持变参函数

变参函数无法很好的处理对象参数

利用函数模板和变参函数能够判断指针变量
原文链接: https://www.cnblogs.com/DXGG-Bond/p/12157509.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/191523

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午5:45
下一篇 2023年2月12日 下午5:45

相关推荐