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

标签 c++ c++17 constexpr variant static-assert

我对 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/

相关文章:

c++ - GCC NRVO/RVO 警告

c++ - 无法从 <brace-enclosed initializer list> 转换

c++ - 类型推导模板函数返回类型

c++ - 尝试从 std::array 将 .data() 编译为 c++20 中的 constexpr 函数时出错

c++ - 可以跨静态断言维护状态吗?

c++ - 如何通过内联函数强制 const 传播?

c++ - 在 boost iostream filtering_ostream 中,sync()、strict_sync() 和 flush() 有什么区别?

c++ - 在编译时引用 const 值——什么时候 const 的定义才真正可用?

c++ - 类似于 "if constexpr"但用于类定义

c++ - 转换参数包类型