如何 static_assert 该类型对于 c++20 中的模板非类型参数是可行的

How to static_assert that type is viable for template non-type parameter in c++20

我有一个类型TimeDuration。现在它是 literal type 我可以将它用作非类型模板参数。这种用法与类型定义相去甚远(编译方面),因此如果有人修改 TimeDuration 使其不再是孤独的文字,它会在很久以后被注意到。

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

我知道 ,但答案基本上是说我的问题不存在。

有一种非常简单的方法可以得到一个类型是否适合在非类型模板参数中使用的编译错误:在 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,以保证静态存储时长。