如何静态断言该类型对于 c++20 中的模板非类型参数是可行的 [英] How to static_assert that type is viable for template non-type parameter in c++20

查看:31
本文介绍了如何静态断言该类型对于 c++20 中的模板非类型参数是可行的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类型 TimeDuration.现在它是 文字类型,我可以将它用作非类型模板范围.这种用法与类型定义相去甚远(在编译方面),因此如果有人修改 TimeDuration 使其不再是字面量,那么稍后就会注意到.

I have a type TimeDuration. Right now it is literal type and I can use it as non-type template parameter. Such usage is very far away (compilation-wise) from type definition, so if anybody modifies TimeDuration such that it is no loner literal, it will be noticed much later.

所以我把 static_assert(std::is_literal_type_v); 放在类定义之后.但是,is_literal_type 在 c++20 中被删除了.我可以用什么代替它?

So I put static_assert(std::is_literal_type_v<TimeDuration>); just after class definition. However, is_literal_type is deleted in c++20. What can I replace this with?

我知道 C++17 中已弃用的 std::is_literal_type,但答案基本上是说我的问题不存在.

I know about Deprecated std::is_literal_type in C++17, but the answer basically says that my problem doesn't exist.

推荐答案

有一个非常简单的方法来获得关于类型是否适合在非类型模板参数中使用的编译错误:在 NTTP 中使用它.如果不合适,编译器会抱怨.

There is a very simple way to get a compile error on whether a type is appropriate for use in a non-type template parameter: use it in a NTTP. The compiler will complain if it's not appropriate.

您可以轻松地在某处编写一个小模板并使用您的类型显式实例化它.类似的东西:

You can easily write a small template somewhere and instantiate it explicitly with your type. Something like:

template<auto val> struct checker{};

template struct checker<MyType(/*insert params for constexpr function here*/)>;

is_literal_type 无论如何都不合适(这就是它消失的原因),因为作为文字类型并不像 C++20 的用户定义 NTTP 规则那样严格.是的,用户定义的 NTTP 必须是文字类型,但它还必须具有许多其他特性.

is_literal_type wouldn't be appropriate anyway (which is why it's going away) because being a literal type isn't nearly as restrictive as C++20's user-defined NTTP rules. Yes, a user-defined NTTP must be a literal type, but it must also have a number of other qualities.

这篇关于如何静态断言该类型对于 c++20 中的模板非类型参数是可行的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆