Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check that a type is 'formattable' using type traits / concepts?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Why doesn’t this work?

>Solution :

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 {
  std::format_context::template 
    formatter_type<std::remove_cvref_t<T>>()
      .format(std::declval<T&>(), std::declval<std::format_context&>());
};

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

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading