size_t to unsigned int (from API function)

Tony The Lion picture Tony The Lion · Apr 19, 2011 · Viewed 19.6k times · Source

I am using the Oracle API to access a database and this API has a function readBuffer(char * buffer, unsigned int size); to which I cannot make any changes.

I have a class that uses this API and the signature of my function currently takes a std::string and an unsigned int for the size, the problem is that when I pass std::string.size() to the size argument of my function, I get a warning from my compiler that converting from size_t to unsigned int could cause data loss.

I wondered if there is a valid way to convert the size_t to an unsigned int so I can pass it to my API and not get a warning from the compiler?

I understand the purpose of size_t and searching google for this conversion turns up a lot of results that say "change the function to take a size_t arg" but I CANNOT change the signature of my API in this case.

Any suggestions?

Answer

sharptooth picture sharptooth · Apr 19, 2011

Yes, write a helper function that will check whether such conversion is valid and throw an exception otherwise. Something like:

unsigned int convert( size_t what )
{
    if( what > UINT_MAX ) {
       throw SomeReasonableException();
    }
    return static_cast<unsigned int>( what );
}