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

Disabling a constructor entirely using `std::enable_if`

本文关键字:quot if 构造函数 std enable      更新时间:2023-10-16

我有一个模板类型,它是用某个指针类型参数化的。(像迭代器)。我希望此类型可以隐式地转换为具有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放在构造函数的参数列表中也没有帮助。用GCC 8和-std=c++17编译。这是一个带有代码的Godbolt链接。

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

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_)) {}