![](/img/trans.png)
[英]static_assert in function template with non-type template parameter
[英]How to static_assert that type is viable for template non-type parameter in c++20
我有一个类型TimeDuration
。 现在它是文字类型,我可以将它用作非类型模板参数。 这种用法与类型定义相距甚远(编译方式),因此如果有人修改TimeDuration
使其不再是单独的文字,那么稍后会注意到它。
所以我把static_assert(std::is_literal_type_v<TimeDuration>);
就在 class 定义之后。 但是, is_literal_type
在 c++20 中被删除。 我可以用什么代替它?
我知道C++17 中已弃用的 std::is_literal_type ,但答案基本上说我的问题不存在。
有一种非常简单的方法可以获取关于类型是否适合在非类型模板参数中使用的编译错误:在 NTTP 中使用它。 如果不合适,编译器会抱怨。
您可以轻松地在某处编写一个小模板并使用您的类型显式实例化它。 就像是:
template<auto val> struct checker{};
template struct checker<MyType(/*insert params for constexpr function here*/)>;
is_literal_type
无论如何都不合适(这就是它消失的原因),因为作为文字类型并不像 C++20 的用户定义 NTTP 规则那样具有限制性。 是的,用户定义的 NTTP 必须是文字类型,但它还必须具有许多其他特性。
如果您不关心模板签名的唯一性(避免 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 {};
但是您不能通过即时临时人员。 您需要将引用变量声明为 static constexpr 以确保 static 存储持续时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.