xtd 0.2.0
Loading...
Searching...
No Matches
format_class_with_specified_formating.cpp

Show how to use format xtd::format class with specified formatting.

#include <xtd/format_exception>
#include <xtd/ustring>
using namespace std;
using namespace xtd;
class character {
public:
character(const ustring& name, const ustring& rank) noexcept : name_(name), rank_(rank) {}
const ustring& name() const noexcept {return name_;}
const ustring& rank() const noexcept {return rank_;}
ustring to_string() const noexcept {return to_string("F");}
ustring to_string(const ustring& fmt) const {
if (fmt == "F") return name_ + " (" + rank_ + ")";
if (fmt == "N") return name_;
if (fmt == "R") return rank_;
}
// Only this operator is needed for character class to be recognized by ustring::format() without specified formating.
friend ostream& operator <<(ostream& os, const character& value) noexcept {return os << value.to_string();}
private:
ustring name_;
ustring rank_;
};
// Only this method is needed for character class to be recognized by ustring::format() with specified formating (F, N or R).
template<>
string xtd::to_string(const character& value, const string& fmt, const locale& loc) {return value.to_string(fmt);}
auto main()->int {
auto c = character {"Jean-Luc Picard", "Captain"};
cout << ustring::format("{}", c) << endl;
cout << ustring::format("{:F}", c) << endl;
cout << ustring::format("{:N}", c) << endl;
cout << ustring::format("{:R}", c) << endl;
}
// This code produces the following output :
//
// Jean-Luc Picard (Captain)
// Jean-Luc Picard (Captain)
// Jean-Luc Picard
// Captain
The exception that is thrown when the format of an argument does not meet the parameter specification...
Definition format_exception.h:18
Represents text as a sequence of UTF-8 code units.
Definition ustring.h:47
#define current_stack_frame_
Provides information about the current stack frame.
Definition current_stack_frame.h:16
@ character
Specifies that the text is trimmed to the nearest character.
std::string to_string(const date_time &value, const std::string &fmt, const std::locale &loc)
Convert a specified value into a string with specified format and locale.
Definition date_time.h:1080
@ c
The C key.
The xtd namespace contains all fundamental classes to access Hardware, Os, System,...
Definition xtd_about_box.h:10