When compiling this code on VC++ 6.0 it gives me:
Code:
error C2667: 'StringToNum' : none of 2 overload have a best conversion
error C2668: 'StringToNum' : ambiguous call to overloaded function
Code:
#include <string>
#include <sstream>
#include <stdexcept>
#include <climits>
template <typename E,
typename T,
typename A,
typename N>
void StringToNum( const std::basic_string<E, T, A>& str,
N& num )
{
std::basic_stringstream<E, T, A> ss( str );
if ( !(ss >> num) )
{
throw std::invalid_argument( "Error converting string to number!" );
}
}
template <typename E,
typename T,
typename A>
void StringToNum( const std::basic_string<E, T, A>& str,
unsigned char& num )
{
std::basic_stringstream<E, T, A> ss( str );
unsigned short snum = 0;
if ( !(ss >> snum) || (snum > UCHAR_MAX) )
{
throw std::invalid_argument( "Error converting string to number!" );
}
num = static_cast<unsigned char>( snum );
}
using namespace std;
int main()
{
unsigned char num = 0;
wstring str( L"Hello world" );
StringToNum( str, num );
return 0;
}
and on Comeau it's quite a bit more verbose...
What's wrong and how can I make StringToNum() work for unsigned char numbers?
When I tried compiling it without the specialization for unsigned chars I got this error:
Code:
error C2679: binary '>>' : no operator defined which takes a right-hand operand of type 'char' (or there is no acceptable conversion)
D:\Programming\C++\Test\src\main.cpp(15) : see reference to function template instantiation 'class std::basic_istream<unsigned short,struct std::char_traits<unsigned short> > &__cdecl std::operator >>(class std::basic_istream<unsigned short,
struct std::char_traits<unsigned short> > &,unsigned char &)' being compiled