我想为std :: stoi,std :: stof,std :: stod等做一个通用函数..就像:
// std::string -> int
std::string str = "1000000";
int i = to_numeric(str);
// std::string -> long
std::string str = "100000000000";
long i = to_numeric(str);
// std::string -> float
std::string str = "10000.1";
float i = to_numeric(str);但我不知道如何做出部分专业化:
template
int to_numeric(const std::string &str, size_t *pos = 0, int base = 10) {
return std::stol(str, pos, base);
};
template<>
long to_numeric(const std::string &str, size_t *pos, base) {
return std::stol(str, pos, base);
};
template<>
float to_numeric(const std::string &str, size_t *pos) {
return std::stof(str, pos);
};
// .....错误:
to_numeric.cpp:76:79: error: default argument specified in explicit specialization [-fpermissive]
to_numeric.cpp:76:12: error: template-id 'to_numeric' for 'float to_numeric(const string&, size_t*)' does not match any template declaration
make: *** [build] Error 1