我想为 std::stoi、std::stof、std::stod 等创建一个通用函数。比如:
// std::string -> int
std::string str = "1000000";
int i = to_numeric<int>(str);
// std::string -> long
std::string str = "100000000000";
long i = to_numeric<long>(str);
// std::string -> float
std::string str = "10000.1";
float i = to_numeric<float>(str);
但我不知道如何进行部分专业化:
template<class T>
int to_numeric(const std::string &str, size_t *pos = 0, int base = 10) {
return std::stol(str, pos, base);
};
template<>
long to_numeric<long>(const std::string &str, size_t *pos, base) {
return std::stol(str, pos, base);
};
template<>
float to_numeric<float>(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<float>' for 'float to_numeric(const string&, size_t*)' does not match any template declaration
make: *** [build] Error 1