Last active
October 9, 2016 23:10
-
-
Save ptomato/20dfcf9a84c64e51b3ffbac2ef022561 to your computer and use it in GitHub Desktop.
Templated scanf-like function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
struct SomeStruct { | |
int val; | |
}; | |
template<typename T> | |
bool | |
assign(const char c, T& ref) { | |
return false; | |
} | |
bool | |
assign(const char c, bool*& ref) { | |
if (c != 'b') | |
return false; | |
*ref = true; | |
return true; | |
} | |
bool | |
assign(const char c, int*& ref) { | |
if (c != 'i') | |
return false; | |
*ref = 42; | |
return true; | |
} | |
bool | |
assign(const char c, SomeStruct& ref) { | |
if (c != 'h') | |
return false; | |
ref.val = 81; | |
return true; | |
} | |
template<typename T> | |
bool | |
tscanf(const char *format, const char *name, T& ref) | |
{ | |
if (format[0] == '\0' || format[1] != '\0') { | |
std::cerr << "Wrong number of arguments" << std::endl; | |
return false; | |
} | |
if (!assign(format[0], ref)) { | |
std::cerr << "Wrong type for argument " << name << std::endl; | |
return false; | |
} | |
return true; | |
} | |
template<typename T, typename... Args> | |
bool | |
tscanf(const char *format, const char *name, T& ref, Args... args) | |
{ | |
if (format[0] == '\0') { | |
std::cerr << "Wrong number of arguments" << std::endl; | |
return false; | |
} | |
if (!assign(format[0], ref)) { | |
std::cerr << "Wrong type for argument " << name << std::endl; | |
return false; | |
} | |
return tscanf(format + 1, args...); | |
} | |
int | |
main(void) | |
{ | |
bool b; | |
int i; | |
SomeStruct h; | |
if (!tscanf("hbi", | |
"handle", h, | |
"switch", &b, | |
"num", &i)) | |
return 1; | |
std::cout << h.val << ' ' << b << ' ' << i << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment