gpt4 book ai didi

c++ 为什么这个 static_assert 有效 :

转载 作者:搜寻专家 更新时间:2023-10-31 01:29:52 25 4
gpt4 key购买 nike

我有以下关于 constexpr 的问题,我有点明白不能声明 std::shared_ptr<T>成为const , 但为什么第一个 static_assert()有用吗?

另外,第二个static_assert()如何工作?我想要一个 std::variants 的数组,它们是常量,并且希望进行编译时类型检查以强制执行类型;然而,似乎如果 std::shared_ptr是变体类型之一,则不能声明constexpr ;但是如果我将容器声明为 std::tuple , 即使没有 constexpr注释,(I)似乎有效;

typedef std::shared_ptr<int> intp;

const auto defaults = std::make_tuple(std::make_pair(1, true),
std::make_pair(2, 3),
std::make_pair(3, intp(nullptr)));


typedef std::variant<int, bool> MyVar;
constexpr MyVar var1 = 3;

// constexpr intp x = nullptr; (I)
//typedef std::variant<int, bool, intp> MyVar2; This doesn't work
//constexpr MyVar2 var2 = 3;

int main()
{
// Q1): Why the following works, but (I) does not.
static_assert(std::is_same<decltype(std::get<2>(defaults).second), intp>::value);
// Q2): Why this works: is there a better way to say something like
// static_assert(actual_type(var1) == int);
static_assert(std::get<int>(var1) == 3);
//static_assert(x == nullptr); This does not work
}

最佳答案

I kinda understand that one cannot declare a shared_ptr to be const, but why does the first static_assert works?

因为

static_assert(std::is_same<decltype(std::get<2>(defaults).second), intp>::value);

不创建编译时 stared_ptr ;只检查 std::get<2>(defaults).second 的类型是 intp .

如果值仅在运行时可用,则此信息也是编译时已知的。

Also, how does the second static_assert work? I wanted to have an array of std::variants, which are consts, and wanted to have compile-time type-checking to enforce the type; however, it seems that if a shared_ptr is one of the variant type, then it cannot be declared constexpr; but if I declare the container as std::tuple, even without the constexpr annotation, (I) seemed to work;

不太清楚你的意思。

如果你是说“第二个 static_assert 工作”

static_assert(std::get<int>(var1) == 3);

因为var1constexprstd::get() (对于 std::variant )是 constexpr ;所以std::get<int>(var1)这是一个可以使用的值,编译时,在 static_assert() 中与

关于c++ 为什么这个 static_assert 有效 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49100298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com