我对 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);
这是因为var1
是 constexpr
和std::get()
(对于 std::variant
)是 constexpr
;所以std::get<int>(var1)
这是一个可以在编译时使用的值 static_assert()
与
关于c++ 为什么这个 static_assert 有效 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49100298/