Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) boost::bad_lexical_cast

 

boost::bad_lexical_cast is a Boost exception thrown when boost::lexical_cast fails.

 

 

 

 

 

Example: CanLexicalCast

 

CanLexicalCast checks if a boost::lexical_cast will be successful, by catching a possible boost::bad_lexical_cast.

 

#include <cassert>
#include <string>
#include <boost/lexical_cast.hpp>
 
//From http://www.richelbilderbeek.nl/CppCanLexicalCast.htm
template <class TargetType>
bool CanLexicalCast(const std::string& from)
{
  try
  {
    boost::lexical_cast<TargetType>(from);
  }
  catch (boost::bad_lexical_cast)
  {
    return false;
  }
  catch (...)
  {
    assert(!"Something unexpected happened");
    throw;
  }
  return true;
}

 

 

 

 

 

Comparison between CanCast and CanLexicalCast

 

The table below shows if a std::string can be converted according to CanCast (CC) and CanLexicalCast (CLC). Note that the first std::string was a space (' '). Below the table I show the code I've used to generate this output. CanCast serves the same purpose as CanLexicalCast, but does not throw an exception and does not use Boost. Note that there are differences between CanCast and CanLexicalCast, as CanLexicalCast is more strict.

 

Type

int

int

double

double

string

CC

CLC

CC

CLC

 

false

false

false

false

a

false

false

false

false

1

true

true

true

true

1,1

true

false

true

false

1.1

true

false

true

true

1.1.1

true

false

true

false

-1

true

true

true

true

-1.1

true

false

true

true

-1.1.1

true

false

true

false

 

#include <vector>
 
int main()
{
  std::vector<std::string> v;
  v.push_back("");
  v.push_back("a");
  v.push_back("1");
  v.push_back("1,1");
  v.push_back("1.1");
  v.push_back("1.1.1");
  v.push_back("-1");
  v.push_back("-1.1");
  v.push_back("-1.1.1");
 
    std::cout << "Type"
      << '\t' << "int"
      << '\t' << "int"
      << '\t' << "double"
      << '\t' << "double"
      << std::endl;
    std::cout << "string"
      << '\t' << "CC"
      << '\t' << "CLC"
      << '\t' << "CC"
      << '\t' << "CLC"
      << std::endl;
 
  std::cout << std::boolalpha;
 
  const std::size_t size = v.size();
  for (std::size_t i=0; i!=size; ++i)
  {
    std::cout << v[i]
      << '\t' << CanCast<int>(v[i])
      << '\t' << CanLexicalCast<int>(v[i])
      << '\t' << CanCast<double>(v[i])
      << '\t' << CanLexicalCast<double>(v[i])
      << '\n';
  }
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict