如何创建泛型函数,它将返回c ++中任何级别指针的值?

Rup*_*av. 2 c++ templates pointers generic-programming

我想要一个函数,它将返回指针的值,无论它指向什么级别的指针.喜欢它可能是单个或双指针或三指针或更多,但该函数应返回该值.

例:

#include <iostream>
using namespace std;

template <class T>
T func(T arg){
      // what to do here or there is some other way to do this?????
}

int main() {
    int *p, **pp, ***ppp;
    p = new int(5);
    pp = &p;
    ppp = &pp;

    cout << func(p);    // should print 5
    cout << func(pp);   // should print 5
    cout << func(ppp);  // should print 5
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

所以,现在我想在一个函数中传递这个p,pp,ppp,它应该打印或返回值'5'.

Bar*_*rry 10

只有一个重载,它接受任何指针,并调用自己的解引用,以及一个带有任何东西的重载:

template <class T>
T func(T arg) {
    return arg;
}

template <class T>
auto func(T* arg){
    return func(*arg);
}
Run Code Online (Sandbox Code Playgroud)

如果没有C++ 11,这甚至是可能的,只需编写一个类型特征来进行所有解除引用:

template <class T>
struct value_type { typedef T type; };

template <class T>
struct value_type<T*> : value_type<T> { };

template <class T>
T func(T arg) {
    return arg;
}

template <class T>
typename value_type<T>::type func(T* arg){
    return func(*arg);
}
Run Code Online (Sandbox Code Playgroud)