Recursively dereference pointer

前端 未结 2 485
再見小時候
再見小時候 2021-01-15 19:42

While trying to answer one question here, I found this question:

How to recursively dereference pointer (C++03)?

Adapted code from the answer is following:

2条回答
  •  被撕碎了的回忆
    2021-01-15 20:13

    This is possible with the use of a custom can_dereference trait:

    template 
    struct can_dereference_helper {
        template ())>
        static std::true_type test(U);
        template 
        static std::false_type test(U...);
        using type = decltype(test(std::declval()));
    };
    
    template 
    struct can_dereference :
      can_dereference_helper::type>::type {};
    

    and some mutually-recursive functions with a bit'o tag dispatching:

    template 
    auto recursive_dereference(T&& t, std::false_type) ->
      decltype(std::forward(t)) {
        return std::forward(t);
    }
    
    template 
    auto recursive_dereference(T&& t) ->
      decltype(recursive_dereference(std::forward(t), can_dereference{}));
    
    template 
    auto recursive_dereference(T&& t, std::true_type) ->
      decltype(recursive_dereference(*std::forward(t))) {
        return recursive_dereference(*std::forward(t));
    }
    
    template 
    auto recursive_dereference(T&& t) ->
      decltype(recursive_dereference(std::forward(t), can_dereference{})) {
        return recursive_dereference(std::forward(t), can_dereference{});
    }
    

    See it work live at Coliru. This may seem like overkill compared to Kerrek's answer, but I went for a generic approach that will dereference anything that supports operator*. I'll let you decide which tool fits your problem best.

提交回复
热议问题