如何检查类型是格式化的'使用类型特征 /概念?

发布于 2025-02-02 23:26:07 字数 367 浏览 2 评论 0 原文

我想检查是否可以与 std ::格式一起使用某种类型。

这是我天真的尝试:

template<typename Object>
concept formattable = requires(const Object & obj)
{
    std::format("{}", obj);
};

但这不起作用。对于所有类型,它基本上返回true。甚至那些不能与std ::格式一起使用的人。

static_assert(!格式&lt; std :: vector&lt; int&gt;&gt;); //返回false

为什么不起作用?

I would like to check if a certain type can be used with std::format.

This is my naive attempt:

template<typename Object>
concept formattable = requires(const Object & obj)
{
    std::format("{}", obj);
};

But this does not work. It basically returns true for all types. Even those that can't be used with std::format.

static_assert(!formattable<std::vector<int>>); // should return false

Why doesn't it work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月竹挽风 2025-02-09 23:26:07

更新:

随着,C ++ 23中已经有一个概念,用于测试类型是否格式,即 std :: formattable


由于 std ::格式不是受约束的函数,因此expression std ::格式(“ {}”,obj),obj)始终是良好的。您可能想做

#include <format>
    
template<typename T>
concept formattable = requires (T& v, std::format_context ctx) {
  std::formatter<std::remove_cvref_t<T>>().format(v, ctx);
};

的主要基于 basic_format_arg 的构造方法的约束 [format.arg]

demo

Update:

With the introduction of Formatting Ranges, there is already a concept in C++23 dedicated to testing whether a type is formattable, namely std::formattable.


Since std::format is not a constrained function, the expression std::format("{}", obj) is always well-formed. You might want to do

#include <format>
    
template<typename T>
concept formattable = requires (T& v, std::format_context ctx) {
  std::formatter<std::remove_cvref_t<T>>().format(v, ctx);
};

which mainly based on the constraints of the basic_format_arg's constructor in [format.arg].

Demo

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文