委托给另一个对象的operator->

Rya*_*ing 1 c++ templates c++11

在别名模板编写将演绎出某种类型的返回类型TS" operator->,到目前为止,我有这

template <typename T>
using arrow = decltype(std::declval<T&>().operator->());
Run Code Online (Sandbox Code Playgroud)

它适用于所有类类型,但不适用于指针.尝试实际调用时存在类似的问题->

template <typename T>
struct D {
    T t;
    arrow<T> f() { 
        // not valid to call .operator->() on pointers
        return t.operator->();
    }
};
Run Code Online (Sandbox Code Playgroud)

如何使这个函数获得声明的正确返回类型,并正确委托类类型和指针?

Rya*_*ing 5

对于指针,operator->()其自身类型的类型以及生成的对象具有相同的值.使用另一个间接层,辅助结构可以专门用于指针类型

template <typename T>
struct ArrowHelper {
    using type = decltype(std::declval<T&>().operator->());
    type operator()(T& t) const {
        return t.operator->();
    }
};

template <typename T>
struct ArrowHelper<T*> {
    using type = T*;
    constexpr type operator()(T* t) const noexcept {
        return t;
    }
};
Run Code Online (Sandbox Code Playgroud)

为了简化使用,可以轻松定义别名模板和函数

template <typename T>
using arrow = typename ArrowHelper<T>::type;

template <typename T>
arrow<T> apply_arrow(T& t) {
    return ArrowHelper<T>{}(t);
}
Run Code Online (Sandbox Code Playgroud)

委托成员函数然后变成

template <typename T>
struct D {
    T t;
    arrow<T> f() { return apply_arrow(t); }    
};
Run Code Online (Sandbox Code Playgroud)