【发布时间】:2021-08-19 09:57:39
【问题描述】:
这是this question 的后续行动。稍微修改过的代码版本,使用 std::swappable_with_v 而不是 std::swappable_v 会产生不一致的结果:
#include <type_traits>
template <class T>
struct A {};
template <class T, class U>
constexpr void
swap (A<T>&, A<U>&) {}
int main (){
static_assert (std::is_swappable_with_v <A <int>,A<double>>);
using std::swap;
A<int> a;
A<double> b;
swap(a,b);
}
静态断言仅通过 msvc https://godbolt.org/z/G6sj86sfq。虽然所有 3 个主要编译器在删除静态断言时都接受代码:https://godbolt.org/z/hbdq4Eoh1
cppreference 备注:
这个特性不会检查交换表达式的直接上下文之外的任何内容:如果使用 T 或 U 会触发模板特化、隐式定义的特殊成员函数的生成等,并且这些有错误,则实际的交换可能不会即使 std::is_swappable_with
::value 编译并计算为 true,也可以编译。
但不应该发生相反的情况,即当在using std::swap 之后成功调用swap 时,该特征应该产生true。
gcc 和 clang 拒绝断言是否错误?
【问题讨论】:
标签: c++ swap typetraits