完全使用 std::enable_if 禁用构造函数

Disabling a constructor entirely using `std::enable_if`

我有一个用特定指针类型参数化的模板类型。 (就像一个迭代器)。我希望这种类型可以隐式转换为带有 const 限定符的自身版本(例如 thing<const int*>(const thing<int*>&)。我希望当指针已经 const 时禁用此构造函数,因为它与默认复制构造函数冲突。目前我有类似于这段代码的东西:

#include <type_traits>

template <typename Ptr>
struct traits {
    using ptr_type = Ptr;
    static constexpr bool is_const = std::is_const_v<std::remove_pointer_t<ptr_type>>;
    template <typename _Ptr> using rebind = traits<_Ptr>;
};

template <typename Traits>
struct thing {
    using ptr_type = typename Traits::ptr_type;
    using non_const_ptr_type = std::add_pointer_t<std::remove_const_t<std::remove_pointer_t<ptr_type>>>;
    using non_const_traits_type = typename Traits::template rebind<non_const_ptr_type>;

    thing(ptr_type p = nullptr) : ptr_(p) {}
    thing(const thing&) = default;

    template <typename = std::enable_if_t<Traits::is_const>>
    thing(const thing<non_const_traits_type>& other) :
        ptr_(const_cast<ptr_type>(other.ptr_)) {}

    ptr_type ptr_;

    template <typename> friend struct thing;
};

int main() {
    thing<traits<      int*>> t;
    thing<traits<const int*>> j(t);
}

thing 类型从 traits 类型获取参数,因为这更准确地代表了我的真实代码。我试图使用 std::enable_if 禁用构造函数,但出于某种原因,编译器一直在抱怨 non-const thing.

上的 enable_if
error: no type named 'type' in 'struct std::enable_if<false, void>'
    using enable_if_t = typename enable_if<_Cond, _Tp>::type;

enable_if 放入构造函数的参数列表中也无济于事。使用 -std=c++17 使用 GCC 8 编译。 Here 是神马 link 代码。

您需要使 std::enable_if 依赖于构造函数的模板参数而不是 class:

template <class T = Traits, typename = std::enable_if_t<T::is_const>>
thing(const thing<non_const_traits_type>& other) :
    ptr_(const_cast<ptr_type>(other.ptr_)) {}