确定存储在 std::vector 中的对象是否可以轻松复制

use*_*105 2 c++ static-assert

此代码无法编译,因为静态断言失败。

#include <vector>
#include <type_traits>

class A {
};

int main()
{
    std::vector<A> v;
    static_assert(std::is_trivially_copyable<decltype(v[0])>::value);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

另一方面,如果我将 替换decltype(v[0])A,则它可以编译。问题在于v[0]是 的类型引用A而不是A. 我怎样才能让它v以某种方式工作?

Nat*_*ica 5

std::vector有一个value_type成员,该成员是元素类型向量的参数列表中给定的类型。使用它可以给你

static_assert(std::is_trivially_copyable<decltype(v)::value_type>::value);
Run Code Online (Sandbox Code Playgroud)

v[0]或者,您可以从类似中删除参考资格

static_assert(std::is_trivially_copyable<std::remove_reference<decltype(v[0])>::type>::value);
// or if you want to remove all cv and ref qualifications
static_assert(std::is_trivially_copyable<std::remove_cvref<decltype(v[0])>::type>::value);
// or if you want to remove all cv, ref, and array qualifications
static_assert(std::is_trivially_copyable<std::decay<decltype(v[0])>::type>::value);
Run Code Online (Sandbox Code Playgroud)

请注意,如果您使用的是较新版本的 C++(例如 C++17 或 C++20),那么您可以使用_t_v类型特征的版本来简化代码

static_assert(std::is_trivially_copyable_v<decltype(v)::value_type>);

static_assert(std::is_trivially_copyable_v<std::remove_reference_t<decltype(v[0])>>);

static_assert(std::is_trivially_copyable_v<std::remove_cvref_t<decltype(v[0])>>);

static_assert(std::is_trivially_copyable_v<std::decay_t<decltype(v[0])>>);
Run Code Online (Sandbox Code Playgroud)