简体   繁体   English

我如何static_assert类型?

[英]How can I static_assert on types?

Inspired by one of the comments on this question I wanted to write this in my code because I may have made wrong assumptions that would need investigating if I ever port the code to a platform where the two types are not the same. 受到关于这个问题的评论之一的启发,我想在我的代码中写这个,因为如果我将代码移植到两种类型不同的平台,我可能做出了错误的假设,需要调查。

static_assert(typeid(float) == typeid(GLfloat), "GLfloat is unexpected type");

However that does not compile because error: call to non-constexpr function 'bool std::type_info::operator==(const std::type_info&) const' 然而,这不会编译,因为error: call to non-constexpr function 'bool std::type_info::operator==(const std::type_info&) const'

I can however write this :- 不过我可以这样写: -

static_assert(sizeof(float) == sizeof(GLfloat), "GLfloat is unexpected size");

And it works just as expected. 它的工作方式与预期一致。 That will most likely be sufficient to give me a compile time error if my assumptions are wrong on a new platform but I was wondering if there was any way to achieve what I really wanted - to compare the actual types? 如果我在新平台上的假设是错误的,那么很可能足以给我一个编译时错误,但我想知道是否有任何方法可以实现我真正想要的 - 比较实际类型?

Use traits: 使用特征:

#include <type_traits>

static_assert(std::is_same<float, GLfloat>::value, "GLfloat is not float");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM