Analyzing a pointer variable is not

A write program determines a pointer variable is not

Supplements:

  • C ++ still supports variable parameter function in C language.
  • C ++ compiler matches the call priority
    1. Overloaded functions.
    2. Function template.
    3. Variable argument function.

Ideas:

  • The variables are divided into two types: pointer and non-pointer.
  • Writing functions:
    • Returns true if the pointer variable called.
    • Return false non-pointer variables call.

Chemical reaction with template function becomes a function parameter:
Here Insert Picture Description
Programming experiment: determination Pointer

#include <iostream>
#include <string>

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;
}


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;
}


Appeals achieve defect versions exist:

  • Variadic function object parameter can not be resolved, it could cause the program to crash!

A further challenge:

  • How to let the compiler exactly matching function, but not the actual call? sizeof.
#include <iostream>
#include <string>

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))

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;
}



References:

  1. C ++ Tutorial depth analysis
Published 270 original articles · won praise 28 · views 40000 +

Guess you like

Origin blog.csdn.net/SlowIsFastLemon/article/details/104319051