代码之家  ›  专栏  ›  技术社区  ›  Chen Li

使用检测到的惯用语可销毁工具

  •  3
  • Chen Li  · 技术社区  · 7 年前

    下面是我的实现 is_destructible_v :

    template<class T>
    struct is_unknown_bound_array : std::false_type
    {};
    template<class T>
    struct is_unknown_bound_array<T[]> : std::true_type
    {};
    
    template<typename T, typename U = std::remove_all_extents_t<T>>
    using has_dtor = decltype(std::declval<U&>().~U());
    
    template<typename T>
    constexpr bool is_destructible_v
        = (std::experimental::is_detected_v<has_dtor, T> or std::is_reference_v<T>)
            and not is_unknown_bound_array<T>::value
            and not std::is_function_v<T>;
    
    template<typename T>
    struct is_destructible : std::bool_constant<is_destructible_v<T>>
    {};
    

    clang compiled happily and passed all libstdcxx's testsuite 虽然 gcc failed to compile

    prog.cc:177:47: error: 'std::declval<int&>()' is not of type 'int&'
    
     177 | using has_dtor = decltype(std::declval<U&>().~U());    
         |                           ~~~~~~~~~~~~~~~~~~~~^
    prog.cc: In substitution of 'template<class T, class U> using has_dtor = decltype (declval<U&>().~ U()) [with T = int&&; U = int&&]':
    

    因此,gcc不能在这方面做SFINAE using has_dtor = decltype(std::declval<U&>().~U()); .

    问题:

    1. 这里哪个编译器对象是标准的?
    1 回复  |  直到 7 年前
        1
  •  4
  •   llllllllll    7 年前

    GCC在处理时似乎已损坏 ~T() 哪里 T 是标量类型的引用。

    following code ,这显然是一辆马车 [expr.pseudo]/2 :

    template<typename T> using tester = decltype(int{}.~T(), char{});
    tester<int&> ch;
    int main() {}
    

    我会用 if constexpr

    template<class T>
    constexpr bool my_is_destructible() {
        if constexpr (std::is_reference_v<T>) {
            return true;
        } else if constexpr (std::is_same_v<std::remove_cv_t<T>, void>
                || std::is_function_v<T>
                || is_unknown_bound_array<T>::value ) {
            return false;
        } else if constexpr (std::is_object_v<T>) {
            return std::experimental::is_detected_v<has_dtor, T>;
        } else {
            return false;
        }
    }
    

    信息技术 works 还有GCC。