【问题标题】:Why does std::is_copy_constructible not behave as expected?为什么 std::is_copy_constructible 的行为不符合预期?
【发布时间】:2019-02-01 07:19:35
【问题描述】:
#include <type_traits>

int main()
{
    std::is_constructible_v<int&, const int&>; // false, as expected.
    std::is_copy_constructible_v<int&>; // true, NOT as expected!
}

根据cppref

如果 T 是对象或引用类型且变量定义为 T obj(std::declval()...);结构良好,为会员提供 常量值等于真。在所有其他情况下,值为 false。

std::is_copy_constructible_v&lt;int&amp;&gt; 应该给出与std::is_constructible_v&lt;int&amp;, const int&amp;&gt; 相同的结果;但是,clang 7.0 给出了不同的结果,如上所示。

这种行为是否符合 C++ 标准?

【问题讨论】:

  • 另一方面,using T = int&amp;; static_assert(std::is_constructible_v&lt;T, const T&amp;&gt;); // true 至少匹配 is_copy_constructible_v 结果。

标签: c++ c++11 standards typetraits compile-time-constant


【解决方案1】:

is_copy_constructible 的引用状态是:

如果 T 不是可引用类型(即,可能是 cv 限定的 void 或具有 cv-qualifier-seq 或 ref-qualifier 的函数类型),则提供等于 false 的成员常量值。否则,提供一个等于std::is_constructible&lt;T, const T&amp;&gt;::value 的成员常量值。

所以,这里的is_copy_constructible&lt;T&gt;::valuestd::is_constructible&lt;T, const T&amp;&gt;::value 相同。

所以在你的情况下:

std::is_constructible&lt;int, const int&amp;&gt;::value 将与std::is_copy_constructible_v&lt;int&gt; 相同。

DEMO

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 2012-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多