Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

How to make std::format work with your own data types(C++20)?

+4 votes
asked Jan 4, 2022 by Areeb Sherjil (1,960 points)
I want to be able to write the following:

std::format("My new box, Box({:.2},{:.2},{:.2})", box.getLength(), box.getWidth(), box.getHeight());

to

std::format("My new box, Box({:.2},{:.2},{:.2})", box.getLength(), box.getWidth(), box.getHeight());

This is what I've done so far:

template <>

class std::formatter<Box> :public std::formatter<double>

{

public:

    using std::formatter<double>::format;

    auto format(const Box& box, auto& context)

    {

        auto iter = format(box.getLength(), context);

        context.advance(iter);

        out = format(box.getWidth(), context);

        context.advance(iter);

        return format(box.getHeight(), context);

    

    }

}; The box class definition is inside another header file. As you can see this code above does not work.

1 Answer

0 votes
answered Jul 6, 2022 by AADI JAIN (350 points)

i would recommend not to use std:: and write using namespace std instead or for your own data type 

first make a header file and save it with   (.H)  extention and then include it in your file  to use your own data type without using  std::

commented Jul 6, 2022 by Peter Minarik (84,720 points)
edited Jul 7, 2022 by Peter Minarik
You just gave terrible advice there suggesting not to use the fully qualified name of an identifier, it is quite a bad idea.

The recommendation is to always use fully qualified names to prevent future problems or even malicious attacks.

Please, read more here (https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice), why you should always qualify the full name and not rely on "using namespace" in real-world applications.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...