如何递归取消引用指针(C++ 03)?

Meh*_*dad 13 c++ templates pointers function-pointers visual-c++-2008

我试图在C++中递归取消引用指针.

如果传递的对象不是指针(这包括智能指针),我只想在可能的情况下通过引用返回对象本身.

我有这个代码:

template<typename T> static T &dereference(T &v) { return v; }
template<typename T> static const T &dereference(const T &v) { return v; }
template<typename T> static T &dereference(T *v) { return dereference(*v); }
Run Code Online (Sandbox Code Playgroud)

在大多数情况下,我的代码似乎工作正常,但是在给定函数指针时会中断,因为取消引用函数指针会导致相同类型的函数指针,从而导致堆栈溢出.

那么,当解除引用类型与原始对象具有相同类型时,如何"停止"解除引用过程?

注意:

我看到我的问题被标记为使用Boost的类似问题的副本; 但是,我需要一个没有Boost(或任何其他库)的解决方案.


例:

template<typename T> T &dereference(T &v) { return v; }
template<typename T> const T &dereference(const T &v) { return v; }
template<typename T> T &dereference(T *v) { return dereference(*v); }

template<typename TCallback /* void(int) */>
void invoke(TCallback callback) { dereference(callback)(); }

void callback() { }

struct Callback {
     static void callback() { }
     void operator()() { }
};

int main() {
    Callback obj;
    invoke(Callback());          // Should work (and does)
    invoke(obj);                 // Should also work (and does)
    invoke(&obj);                // Should also work (and does)
    invoke(Callback::callback);  // Should also work (but doesn't)
    invoke(&Callback::callback); // Should also work (but doesn't)
    invoke(callback);            // Should also work (but doesn't)
    invoke(&callback);           // Should also work (but doesn't)
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

ron*_*nag 6

根本没有依赖,简单,应该适用于MSVC-2008.

template<typename T>
struct is_function
{
    static char     check(...);
    static double   check(const volatile void*); // function pointers are not convertible to void*
    static T        from;
    enum { value = sizeof(check(from)) != sizeof(char) };
};

template<bool, typename T = void>
struct enable_if{};

template<typename T>
struct enable_if<true, T>{typedef T type;};

template<typename T> 
T& dereference(T &v){return v;}

template<typename T> 
const T& dereference(const T& v){return v;}

template<typename T> 
typename enable_if<!is_function<T>::value, T&>::type dereference(T* v){return dereference(*v);}
Run Code Online (Sandbox Code Playgroud)