[英]C++ template function to split string to array
我讀了一個包含行的文本文件,每行包含用定界符分隔的數據,例如空格或逗號,我有一個將字符串拆分為數組的函數,但我想使其成為模板,以獲取字符串旁邊的不同類型(例如浮點數或整數),我做了兩個函數,一個用於拆分為字符串,另一個用於浮點
template<class T>
void split(const std::string &s, char delim, std::vector<T>& result) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
T f = static_cast<T>(item.c_str());
result.push_back(f);
}
}
void fSplit(const std::string &s, char delim, std::vector<GLfloat>& result) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
GLfloat f = atof(item.c_str());
result.push_back(f);
}
}
模板函數可以很好地處理字符串,在另一個函數中,我可以使用atof(item.c_str())
從字符串中獲取浮點數,當我將模板函數與浮點數結合使用時,我會invalid cast from type 'const char*' to type 'float'
那么如何在模板函數中進行轉換呢?
您不能:
T f = static_cast<T>(item.c_str());
在您的情況下,您可以聲明一個模板,例如from_string<T>
,並將該行替換為:
T f = from_string<T>(item);
您將通過以下方式實現它:
// Header
template<typename T>
T from_string(const std::string &str);
// Implementations
template<>
int from_string(const std::string &str)
{
return std::stoi(str);
}
template<>
double from_string(const std::string &str)
{
return std::stod(str);
}
// Add implementations for all the types that you want to support...
您可以使用strtof函數( http://en.cppreference.com/w/cpp/string/byte/strtof )
所以像這樣
GLfloat f = std::strtof (item.c_str(), nullptr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.