[C ++ in-depth analysis] 50. Determine whether a variable is a pointer

  • Variable parameter functions in C are still supported in C ++
  • C ++ compiler matching call priority
    1. Overloaded function
    2. Function template
    3. Variable parameter function

Idea: Divide variables into two categories, pointers and non-pointers, using function templates and variable parameter functions. When the pointer is passed in, the function template is first matched. When the non-pointer variable is passed in, the variable parameter function is matched.

Insert picture description here

// 50-1.cpp
#include<iostream>
using namespace std;
class Test
{
public:
    Test()
    {
    }
    virtual ~Test()
    {
    }
};

template<typename T>
char IsPtr(T* v)
{
    return 'd';
}
int IsPtr(...)				// 三个点表示可接受任何函数
{
    return 0;
}
#define ISPTR(p) (sizeof(IsPtr(p)) == sizeof(char))

int main()
{
    int i = 0;
    int* p = &i;
    cout << "p is a pointer: " << ISPTR(p) << endl;
    cout << "i is a pointer: " << ISPTR(i) << endl;
    Test t;
    Test* pt = &t;
    cout << "pt is a pointer: " << ISPTR(pt) << endl;
    cout << "t is a pointer: " << ISPTR(t) << endl;
    return 0;
}

Match the function template when passing in the pointer, and match the variable parameter function when passing in the variable.

However, the variable parameter function cannot parse the object parameters, and it cannot pass the class object to the variable parameter function. In fact, we can distinguish when we match the function. Can we only match without calling the function? We used a macro. At compile time, sizeof (IsPtr§ can already determine the size, and the pointer matches char IsPtr (T * v). Knowing that it returns char, the size is 1, and the variable matches int IsPtr (...), you know that it returns int, the size is 4. This way you can only match without calling the function.

Compile and run:

$ g++ 50-1.cpp -o 50-1
$ ./50-1
p is a pointer: 1
i is a pointer: 0
pt is a pointer: 1
t is a pointer: 0

Summary:
1. Variable parameter functions are still supported in C ++
2. Pointer variables can be judged using function templates and variable parameter functions

Published 298 original articles · praised 181 · 100,000+ views

Guess you like

Origin blog.csdn.net/happyjacob/article/details/104662878