template<class T>
inline T Library<T>::get_isbn()
{
T temp;
cout << "Enter the name/no:" << endl;
cin >> temp;
string ka;
if (typeid(temp) == typeid(ka))
{
while (islower(temp[0]))
{
cout << " Pls enter the using the first letter as capital" << endl;
cin >> temp;
}
}
}
return temp;
}我正在创建一个模板类,它可以以整数或string作为模板参数,当我以T作为string创建类的一个对象时,它在循环中运行,一切都正常。但是,当我创建一个以int作为模板参数的对象时,它会给出以下两个错误:
错误C1903:无法从以前的错误中恢复;停止编译 错误C2228:'.at‘的左边必须有类/struct/union
我希望如果传递的参数是string,那么只有检查第一个字母为大写字母的代码才能运行,否则当我将模板参数设为int时,它不应该检查第一个字母。
发布于 2013-11-09 10:11:30
if在C++中总是(在语义上)一个运行时决策。编译器可以在编译时对其进行评估,并丢弃未使用的分支。但这并不意味着必须这样做。您仍然必须确保所有分支都包含有效代码。
在本例中,如果temp[0]是整数,则表达式temp的格式不正确.最简单的解决方案是在泛型函数中调用重载函数--注意:通过引入typeid-branching,您的算法本质上不再是泛型的,它需要对某些类型进行特殊处理。
template<class T>
void get_isbn_impl(T&)
{
// default implementation
}
void get_isbn_impl(string& str)
{
// special version for `string`
while (islower(str[0]))
{
cout << " Pls enter the using the first letter as capital" << endl;
cin >> str;
}
}
template<class T>
inline T Library<T>::get_isbn()
{
T temp;
cout << "Enter the name/no:" << endl;
cin >> temp;
get_isbn_impl(temp);
return temp;
}还可以专门化Library<string> (整个类)或只专门化Library<string>::get_isbn。
https://stackoverflow.com/questions/19874637
复制相似问题