首页 > 解决方案 > SFINAE 的不同 g++ 和 clang 行为

问题描述

我正在编写应该检查的模板,如果有类型默认构造函数。

void _void_f(){}

template<typename T, typename ENABLE = void>
struct is_constructible_default {
    static const bool value = false;
};

template<typename T>
struct is_constructible_default<T, typename std::enable_if<std::is_same<decltype((T()), _void_f()),void>::value>::type> {
    static const bool value = true;
}

这适用于具有实现构造函数、生成构造函数或没有默认构造函数的类。但是,当默认构造函数是私有的时,g++ 编译器会出现错误退出,即 T() 是私有的。但是由于 SFINAE,错误应该忽略该重载。对于 clang,此实现工作正常。如何为 g++ 实现 std::is_default_constructible?

https://godbolt.org/g/qAZaJb

哪个编译器在这里?


我可能找到了 g++ 的解决方案。STL 实现使用 SFINAE 作为方法而不是使用 enable_if。

struct is_default_constructible_impl
{
    template<typename T, typename = decltype(T())>
    static std::true_type test(int);

    template<typename>
    static std::false_type test(...);
};

template<typename T>
struct is_constructible_default : decltype(is_default_constructible_impl::test<T>(0))
{};

https://godbolt.org/g/DQ4yZp

标签: c++templatessfinae

解决方案


推荐阅读