Python 사용하다가 format이 편해져서 C++에도 있으면 좋겠다 싶어서 만들었습니다.
아래는 소스코드들이예요.
#pragma once
#include <string>
namespace std {
std::string to_string(const char *ptr) { return std::string(ptr); }
std::string to_string(char ch) { return std::string() + ch; }
}
namespace nekop {
class string : public std::string {
public:
string();
string(const char *_Ptr);
string(const std::allocator<char> &_Al);
string(const char *_Ptr, const std::allocator<char> &_Al);
string(std::string &&_Right);
string(std::initializer_list<char> _Ilist, const std::allocator<char> &_Al);
string(const std::string &_Right);
string(std::string &&_Right, const std::allocator<char> &_Al);
string(const std::string &_Right, const std::allocator<char> &_Al);
public:
template< typename T >
std::string format(const T& t) {
size_t start = 0;
size_t pos = this->find("{}", start);
std::string org = *this;
std::string ret = org;
if (pos != std::string::npos) {
std::string *ptr = this;
std::string value = std::to_string(t);
ret = substr(start, pos) + value + substr(pos + 2);
}
*this = org;
return ret;
}
template< typename _First, typename ... Rest >
std::string format(const _First &first, const Rest & ... rest) {
size_t start = 0;
size_t pos = this->find("{}", start);
std::string org = *this;
if (pos != std::string::npos) {
std::string *ptr = this;
std::string value = std::to_string(first);
*ptr = substr(start, pos) + value + substr(pos + 2);
return format(rest...);
}
return *this;
}
};
}
#include <iostream>
#include "format.h"
namespace nekop {
string::string() : std::string() { }
string::string(const char *_Ptr) : std::string(_Ptr) { }
string::string(const std::allocator<char> &_Al) : std::string(_Al) { }
string::string(const char *_Ptr, const std::allocator<char> &_Al) : std::string(_Ptr, _Al) { }
string::string(std::string &&_Right) : std::string(_Right) { }
string::string(std::initializer_list<char> _Ilist, const std::allocator<char> &_Al) : std::string(_Ilist, _Al) { }
string::string(const std::string &_Right) : std::string(_Right) { }
string::string(std::string &&_Right, const std::allocator<char> &_Al) : std::string(_Right, _Al) { }
string::string(const std::string &_Right, const std::allocator<char> &_Al) : std::string(_Right, _Al) { }
}
int main() {
nekop::string str = "Hello World!!! {} {} {} {} {} {} {} {} {} {} {}";
int a = 123;
unsigned int b = 123;
long c = 123;
unsigned long d = 123;
long long e = 123;
unsigned long long f = 123;
float g = 123.0;
double h = 123.0;
long double i = 123.0;
std::cout << str.format("KuroNeko says...", 'Y', a, b, c, d, e, f, g, h, i) << std::endl;
std::cin >> str;
return 0;
}