rabbitfoot530's diary

読んだ本と、プログラムに関することのメモです。好きな言語は、C++, Python, Golang, TypeScript。数学・物理・学習理論も好きです。

operatorオーバーロードでパス結合

boost::filesystem::pathみたいな感じでパスの結合をやりたかったので書いてみた。

#include <iostream>                                                                                                                                                                  
#include <cstring>

class Path {
private:
  std::string _path;

public:
  std::string str() {
    return _path;
  }

  const char* c_str() {
    return _path.c_str();
  }

  Path& operator=(std::string path) {
    _path = path;
    return *this;
  }

  Path& operator/(Path tail) {
    const char tail_word = this->_path.at(this->_path.length() - 1);
    if ('/' == tail_word) {
      this->_path += tail._path;
    }
    else {
      this->_path += "/" + tail._path;
    }

    return *this;
  }
};


int main() {
  Path head, tail;
  head = "head/";
  tail = "tail";
  head = head/tail;

  std::cout << head.str() << std::endl;
  std::cout << head.c_str() << std::endl;

  head = "head";
  tail = "tail";
  head = head/tail;

  std::cout << head.str() << std::endl;
  std::cout << head.c_str() << std::endl;
  return 0;
}