La libreria Boost offre, nell’header lexical_cast.hpp, la funzione generica lexical_cast, che consente di convertire un numero in una stringa e viceversa:

namespace boost
{
    class bad_lexical_cast;
    template<typename Target, typename Source>
      Target lexical_cast(const Source& arg);
}

Come si può notare, la funzione accetta un argomento di tipo generico Source e restituisce un risultato di tipo Target, ad esempio:

string s = "1";
int x = lexical_cast<int>(s);

in questo esempio, avviene la conversione dalla stringa “1″ ad un intero.

Il fallimento di una conversione comporta il lancio di un’eccezione bad_lexical_cast:

class bad_lexical_cast : public std::bad_cast
{
public:
    ... // stessa interfaccia di std::exception
};

Vediamo un esempio:

#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>

using namespace boost;
using namespace std;

int main()
{
	int x = lexical_cast<int>("1");
	string y = lexical_cast<string>(2);

	cout << x << endl;
	cout << y << endl;

	try {
		double z = lexical_cast<double>("3-14");
		cout << z << endl;
	}
	catch(bad_lexical_cast& e)
	{
		cout << e.what() << endl;
	}

	return 0;
}

L’output del programma è:

1
2
bad lexical cast: source type value could not be interpreted as target

la terza conversione, ovviamente, fallisce, lanciando un’eccezione.