[英]How to static_assert that type is viable for template non-type parameter in c++20
I have a type TimeDuration
.我有一个类型
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.这种用法与类型定义相距甚远(编译方式),因此如果有人修改
TimeDuration
使其不再是单独的文字,那么稍后会注意到它。
So I put static_assert(std::is_literal_type_v<TimeDuration>);
所以我把
static_assert(std::is_literal_type_v<TimeDuration>);
just after class definition.就在 class 定义之后。 However,
is_literal_type
is deleted in c++20.但是,
is_literal_type
在 c++20 中被删除。 What can I replace this with?我可以用什么代替它?
I know about Deprecated std::is_literal_type in C++17 , but the answer basically says that my problem doesn't exist.我知道C++17 中已弃用的 std::is_literal_type ,但答案基本上说我的问题不存在。
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.有一种非常简单的方法可以获取关于类型是否适合在非类型模板参数中使用的编译错误:在 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
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. is_literal_type
无论如何都不合适(这就是它消失的原因),因为作为文字类型并不像 C++20 的用户定义 NTTP 规则那样具有限制性。 Yes, a user-defined NTTP must be a literal type, but it must also have a number of other qualities.是的,用户定义的 NTTP 必须是文字类型,但它还必须具有许多其他特性。
If you don't care about the unicity of the template signature (avoiding std::is_same with classes), you can simply pass a TimeDuration variable (or anything you want) by const reference:如果您不关心模板签名的唯一性(避免 std::is_same 与类),您可以简单地通过 const 引用传递一个 TimeDuration 变量(或任何您想要的):
template <const auto& TimeDurationRef>
requires std::is_same_v<std::decay_t<decltype(TimeDurationRef)>, TimeDuration>
void foo();// or struct Foo {};
But you cannot pass on-the-fly temporaries.但是您不能通过即时临时人员。 You need to declare the referenced variable as static constexpr to ensure static storage duration.
您需要将引用变量声明为 static constexpr 以确保 static 存储持续时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.