Using static class variables without highlighting them

Background

So, today I used a thin shell for std::ofstream, which made it easy for me to write .csv files. I wanted to redefine a statement <<to write a value followed by a comma, and then when the time came for a new line, I would print a backspace character and then a new line. I decided to implement the new line behavior as a custom template as follows:

// *this << value; => prints the value to the csv file
// *this << CsvWriter::BREAK; => goes to the next line of the csv file
// Example:
//   CsvWriter csv("test.csv", {"Col 1", "Col 2", "Col 3"});
//   csv << "Value 1" << 2 << 3.25 << CsvWriter::BREAK;
class CsvWriter {
 public:
  CsvWriter(const char *fname, std::vector<const char *> headers);
  CsvWriter() = delete;
  CsvWriter(const CsvWriter &) = delete;
  CsvWriter &operator=(const CsvWriter &) = delete;
  ~CsvWriter() = default;

  // Used for the template specialization below
  static struct LineBreak {} BREAK;

  template <typename T>
  CsvWriter &operator<<(T t);

 private:
  std::ofstream out_;
  bool first_ = true;  // true when printing first element of line
};

template <typename T>
CsvWriter &CsvWriter::operator<<(T t) {
  if (!first_) {
    out_ << ',';
  } else {
    first_ = false;
  }
  out_ << t;
  return *this;
}

// This is the specialization for newlines.
// If anything of type LineBreak is passed to this function, this executes.
template <>
CsvWriter &CsvWriter::operator<<(LineBreak) {
  out_ << std::endl;
  first_ = true;  // Reset first for next line
  return *this;
}

// The constructor gives an example use of the template specialization
CsvWriter::CsvWriter(const char *fname, std::vector<const char *> headers)
    : out_(fname) {
  for (const char *header : headers) {
    *this << header;  // Prints each string in header
  }
  *this << BREAK;  // Goes to the next line of the csv
}

Brief explanation

, , gcc. , BREAK. , , &CsvWriter::BREAK ( , -, ). , , CsvWriter::LineBreak CsvWriter::BREAK; , &CsvWriter::BREAK ( , .

, , - , . (, ), .

, , , ++ 11? ? , ?

+4
1

.

, , , , . , BREAK <<. , .

, , , .

++ , , . , ++.

0

Source: https://habr.com/ru/post/1659300/


All Articles