我想爲std :: stoi,std :: stof,std :: STOD等,如:相關函數族的通用函數(例如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
我只是使用'boost :: lexical_cast'。 – chris
我沒有提升,但我的C++ 11具有相同的功能 – Robbin
由於您需要指定目標類型,爲什麼要麻煩?對於泛型函數,讓用戶傳遞一個回調來完成轉換,這可能是'std :: stoi'和family。另外,由於這不是明確的關於C++ 11的功能(你只是在實現中使用一個功能,但你也可以調用其他任何東西),所以我編輯了這些標記。 – Xeo