我有以下模板函数:C++模板变换字符串编号
template <typename N>
inline N findInText(std::string line, std::string keyword)
{
keyword += " ";
int a_pos = line.find(keyword);
if (a_pos != std::string::npos)
{
std::string actual = line.substr(a_pos,line.length());
N x;
std::istringstream (actual) >> x;
return x;
}
else return -1; // Note numbers read from line must be always < 1 and > 0
}
好像行:
std::istringstream (actual) >> x;
不工作。 但是同样的功能没有模板:
int a_pos = line.find("alpha ");
if (a_pos != std::string::npos)
{
std::string actual = line.substr(a_pos,line.length());
int x;
std::istringstream (actual) >> x;
int alpha = x;
}
作品就好了。 它是一个问题与std :: istringstream和模板?
我正在寻找一种方法来读取配置文件和加载参数,它们可以是int或real。
编辑解决方案:
template <typename N>
inline N findInText(std::string line, std::string keyword)
{
keyword += " ";
int a_pos = line.find(keyword);
int len = keyword.length();
if (a_pos != std::string::npos)
{
std::string actual = line.substr(len,line.length());
N x;
std::istringstream (actual) >> x ;
return x;
}
else return -1;
}
你是怎么调用这个函数的?什么是'N'?你有编译错误吗? – interjay
没有编译错误。我将这个函数称为:alpha = var :: findInText(line,“alpha”); –