使用Detected Idiom实现is_destructible

问题描述 投票:3回答:1

这是我对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不能在using has_dtor = decltype(std::declval<U&>().~U());上做SFINAE。

题:

  1. 哪个编译器对象标准在这里?
  2. 什么是最优雅的解决方案/解决方法?我能想到的方式有点难看
c++ language-lawyer c++17 template-meta-programming typetraits
1个回答
3
投票

在处理~T()时,GCC似乎被打破了,其中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;
    }
}

它也与GCC一起works

© www.soinside.com 2019 - 2024. All rights reserved.