c++ - 为什么 SFINAE 没有给出递增布尔值的正确结果?
问题描述
我写了一个is_incrementable
这样的特征:
#include <type_traits>
template <typename T, typename = void>
struct is_incrementable : std::false_type {};
template <typename T>
struct is_incrementable<T, std::void_t<decltype(++std::declval<T&>())>>
: std::true_type {};
template <typename T>
constexpr bool is_incrementable_v = is_incrementable<T>::value;
当我将它应用到bool
with -std=c++17
on clang 时,它返回true
:
// This compiles
static_assert(is_incrementable_v<bool>, "");
bool
但在 c++17 下不允许递增。事实上,如果我尝试这样做,我会收到一个错误:
bool b = false;
++b;
结果是:
error: ISO C++17 does not allow incrementing expression of type bool [-Wincrement-bool]
bool
当编译器明确不允许时,为什么 SFINAE 报告它是可递增的?
编译器资源管理器:https ://godbolt.org/g/DDFYBf
解决方案
看起来 Clang 错误地允许bool
在未评估的上下文中增加值。
我们可以使用 C++20 概念简化您的示例:
template<class T>
concept is_incrementable = requires(T t) {
{ ++t };
};
int main() {
static_assert( is_incrementable<int> );
static_assert( !is_incrementable<bool> ); // Clang error here
}
该程序在 GCC 和 MSVC 中被接受,但 Clang 在这里显示相同的错误行为,演示:https ://gcc.godbolt.org/z/YEnKfG8T5
我认为是 Clang 的 bug,所以提交了一个 bug 报告:https ://bugs.llvm.org/show_bug.cgi?id=52280
推荐阅读
- android - 在现代 Android Studio 中编译 MARSYAS 以用于 native-lib
- python - 无法使用 PyAsn1 Python 从 pkcs7 信封中获取加密密钥
- php - 如何使用 php 和 mysql 从表中捕获 ID
- javascript - React Router - 在新选项卡上打开链接并重定向到主页
- active-directory - 如何与 AD 重新同步系统用户信息
- asp.net-mvc - 允许在 MVC 中使用用户名或电子邮件和密码登录
- java - 对 Java 规范中的泛型子类型感到困惑?
- python - 在磁盘上写一个python运行进程
- unix - 我想在 unix cron 上安排一份工作,工作日上午 9 点到下午 5 点,周末 24 小时。你能帮我解决这个问题吗
- java - 不要为添加到列表视图中的新项目设置标签