完全使用"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
放在构造函数的参数列表中也没有帮助。用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_)) {}
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 如何将enable-if与模板参数和参数包一起使用
- 无论条件是否为true,if总是在c++中执行
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 如何删除peer if else分支中的冗长句子
- 我似乎对if/else的基本语句有问题:/
- if数组上的随机数
- 将按位if条件转换为普通if条件
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 使用if-else将数字转换为单词
- 为什么简单的算术减法在"if"条件下不起作用?
- 以在Qt中的IF语句中设置时间延迟
- Craps游戏问题,忽略if语句