C++11 可变参数模板构造string列表
#include <iostream> #include <cstdint> #include <list> #include <string> template<typename T> typename std::enable_if<std::is_integral<T>::value, std::string>::type to_string(const T & val) { return std::to_string(val); } template<typename T> typename std::enable_if<std::is_floating_point<T>::value, std::string>::type to_string(const T & val) { return std::to_string(val); } template<typename T> typename std::enable_if<std::is_enum<T>::value, std::string>::type to_string(const T & val) { return std::to_string(val); } std::string to_string(const std::string & val) { return val; } std::string to_string(char * val) { return val; } template<typename T> void build_str_list(std::list<std::string> & ret, const T & val) { ret.push_back(to_string(val)); } template<typename T, typename... Args> void build_str_list(std::list<std::string> & ret, const T & head, Args&&... args) { ret.push_back(to_string(head)); build_str_list(ret, args...); } template<typename... Args> std::list<std::string> build_string_list(Args&&... args) { std::list<std::string> ret; build_str_list(ret, args...); return ret; } int32_t main() { int16_t a = 1; uint16_t b = 2; int32_t c = 3; int64_t d = 4; uint32_t e = 5; uint64_t f = 6; std::string str = "thank"; const char * you = "you"; char buf[32] = "asd"; enum { ENUM_A = 1002, }; std::list<std::string> ret = build_string_list(12, "hehe", a, b, c, d, e, f, str, you, ENUM_A, "2323323", buf); for (const std::string & str : ret) { std::cout << str << std::endl; } return 0; }