是否存在std::unconvertible_to?如何限制模板参数排除指定类型?
C++ Concepts:排除特定类型的实现方法
C++标准库中并没有内置的std::unconvertible_to概念,不过可以通过现有工具轻松实现你需要的“排除特定类型/可转换类型”的需求,分两种常见场景说明:
1. 仅排除类型本身等于SomeType的情况
如果你的需求是允许所有类型,唯独**完全等于SomeType**的类型不能通过约束,直接借助std::same_as取反即可:
#include <concepts> template <typename T> concept notSomeType = !std::same_as<T, SomeType>;
2. 排除所有可转换为SomeType的类型
如果你的需求是排除所有能隐式/显式转换为SomeType的类型(不止是类型本身),直接对std::convertible_to取反就行,这比写复杂的requires表达式更简洁:
#include <concepts> template <typename T> concept notConvertibleToSomeType = !std::convertible_to<T, SomeType>;
也可以用requires表达式包裹(效果完全一致,写法更贴近你原本的尝试):
template <typename T> concept notConvertibleToSomeType = requires { requires !std::convertible_to<T, SomeType>; };
注:你原本写的notSomeType概念其实是在判断T可以转换为SomeType,和你想要的“排除”逻辑完全相反,只需要添加!取反就能达到目的。
内容的提问来源于stack exchange,提问作者Luh0
相关产品推荐
相关产品推荐

