Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- async
- type_traits
- Android
- AES
- haskell
- WebView
- CustomTab
- Reflect
- ranges
- kotlin
- design pattern
- Scala
- sha256
- coroutines
- traits
- program
- Clojure
- Functional
- SHA512
- Observer
- template
- SHA1
- sprintf
- ChromeTab
- Chrono
- RAII
- web
- stringprintf
- go
- c++
Archives
- Today
- Total
프로그래밍 검색 블로그
stringprintf string반환 sprintf 1 본문
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | #include <string> #include <type_traits> #include <sstream> template<typename _Enum, typename = typename std::enable_if<std::is_enum<_Enum>::value>::type> inline std::ostringstream& operator<<(std::ostringstream& o, _Enum e){ o << ((long long)e); return o; } std::string stringprintf_internal(std::stringstream&& os, const char* str){ for(; *str; str++){ if(*str == '%' && *(++str) != '%'){ //stringprintf("%d")같은 상황을 체크했을때 //throw std::runtime_error("%d"); } else{ os << *str; } } return os.str(); } template<typename Arg, typename... Args> std::string stringprintf_internal(std::stringstream&& os, const char* str, Arg&& arg, Args&&... args){ for(; *str; str++){ //%%는 % //그외에는 Arg가 들어감 if(*str == '%' && *(++str) != '%'){ os << arg; return stringprintf_internal(std::move(os), ++str, std::forward<Args>(args)...); } else{ os << *str; } } //stringprintf("abcde", 1,2,3,4,5); 같이 들어왔을때 throw 하려면 //throw std:: runtime_error("argument"); return os.str(); } template<typename... Args> std::string stringprintf(const char* str, Args&&... args) { if(str == nullptr){ // null str이 들어왔을때 던질려면 //throw std:: runtime_error("null"); return std::string(""); } std::stringstream os; return stringprintf_internal(std::move(os), str, std::forward<Args>(args)...); } | cs |
테스트
1 2 3 4 5 6 7 8 | #include <iostream> using namespace std; int main(int argc, const char * argv[]) { auto s = stringprintf("%d 1%d23 %d 4%d 5%d6 test 1%%", 1,2,3,4,5); cout << s<<endl; } | cs |
위의 테스트에서 %d 대신 %c를 반환해도 출력이 같다.
그냥 써도 문제는 없지만 강력한 형식검사를 위하는 사람도 있으므로 다음 포스트에서 강력한 런타임 타입검사를 하는 stringprintf를 제작해본다
'C++ 유틸' 카테고리의 다른 글
함수가 끝날때 같이 해제하기 defer (0) | 2017.10.06 |
---|---|
시간 관련 API (0) | 2017.10.04 |
stringprintf string반환 sprintf 2 (0) | 2017.10.04 |
C++ Traits (0) | 2017.10.03 |
type_trait / is_nullptr nullptr인지 검사 (0) | 2017.10.03 |
Comments