std :: is_assignable和std :: pair< const T,U> [英] std::is_assignable and std::pair<const T, U>
问题描述
如预期的那样,以下代码无法编译。
As expected, the following code does not compile.
#include <type_traits>
#include <utility>
int main()
{
using T = std::pair<const int, int>;
const auto ok = std::is_assignable<T, T>::value; // true
T x;
T y;
x = y; // compiler error
}
但是 ok
是真的,并具有以下三个编译器。
But the value of ok
is true with the following three compilers.
- g ++(Ubuntu 5.4.0-6ubuntu1〜16.04.4)5.4.0 20160609
- clang版本3.8.0-2ubuntu4(标签/ RELEASE_380 / final)
- MSVC ++ 2017 15.2 26430.6
为什么?
推荐答案
-
is_assignable
提出问题是否存在接受这些参数的赋值运算符签名,而不是该赋值运算符是否会实际编译(以标准语,它仅考虑赋值表达式的立即上下文):
is_assignable
asks the question "is there an assignment operator signature that accepts these arguments", not "will that assignment operator actually compile" (in standardese, it only considers the immediate context of the assignment expression):
template<class T>
struct foo {
T t {};
foo& operator=(const foo& r) { t = r.t; };
};
static_assert(std::is_copy_assignable<foo<const int>>::value, ""); // OK
void bar() {
foo<const int> f1, f2;
f1 = f2; // explodes
}
对
的赋值运算符不能为默认值,因为当该对包含引用时,它需要做一些特殊的事情。这意味着需要采取额外的预防措施,以确保 is_assignable
不说谎(例如,如果成员类型不可复制,则确保删除复制分配运算符)。该标准直到最近最近。
pair
's assignment operators can't be defaulted, because it needs to do something special when the pair contains a reference. That means that additional precautions need to be taken to ensure that is_assignable
doesn't lie (e.g., making sure that the copy assignment operator is deleted if a member type is not copy assignable). The standard has not mandated such precautions until very recently.
is_assignable< T,T>
询问是否 T
rvalue 。这是一个奇怪的问题。
is_assignable<T, T>
asks whether a T
rvalue can be assigned to a T
rvalue. This is an odd question to ask.
这篇关于std :: is_assignable和std :: pair< const T,U>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!