Why in C++ function boost::algorithm::join_if a std::bad_cast exception is thrown?

717 views Asked by At

I found a problem in my code. When I use boost::algorithm::join it works normally, but when I use boost::algorithm::join_if a bad_cast is thrown. My code is below:

#include <iostream>
#include <string>
#include <list>
#include <boost/algorithm/string.hpp>

using namespace std;


main(int argc, char **argv)
{   
    list<string> players;
    players.push_back("ProPlayer98");
    players.push_back("King of Darkness");
    players.push_back("Noob999");
    players.push_back("Daily Queen");

    cout << boost::algorithm::join(players, ", ") << endl; // it works
    cout << boost::algorithm::join_if(players, ", ", boost::is_alpha()) << endl; // bad_cast
}

The output of my program is:

ProPlayer98, King of Darkness, Noob999, Daily Queen
terminate called after throwing an instance of 'std::bad_cast'
  what():  std::bad_cast
Abort trap (core dumped)

I have used some times boost::algorithm functions to play with text, few times I was using predicates, but none of problems like that ever occurred.

I even tried to replace const char* to std::string:

cout << boost::algorithm::join_if(players, string(", "), boost::is_alpha()) << endl;

but problem is still the same.

EDIT: I would like a solution which works also in C++ older than C++11

1

There are 1 answers

1
P0W On BEST ANSWER

boost::is_alpha is for characters

Use like following:-

cout << boost::algorithm::join_if(players, ", ",
                          [](const std::string & s){
                          return boost::all(s,boost::is_alpha()); 
                          }) << endl;

Here obviously, you won't get any output as space ' ' and numerals are present in players.

Use boost::alnum() instead.