fork(4) download
  1. #include <iostream>
  2. #include <type_traits>
  3. #include <utility>
  4. #include <string>
  5. #include <algorithm>
  6. #include <functional>
  7.  
  8. template<bool...> struct BoolSequence{}; //just here to hold bools
  9. template<char...> struct CharSequence{}; //just here to hold chars
  10. template<typename T, char C> struct Contains; //generic
  11. template<char First, char... Cs, char Match> //not first specialization
  12. struct Contains<CharSequence<First, Cs...>,Match> :
  13. Contains<CharSequence<Cs...>, Match>{}; //strip first and increase index
  14. template<char First, char... Cs> //is first specialization
  15. struct Contains<CharSequence<First, Cs...>,First>: std::true_type {};
  16. template<char Match> //not found specialization
  17. struct Contains<CharSequence<>,Match>: std::false_type{};
  18.  
  19. template<int I, typename T, typename U>
  20. struct MakeSequence; //generic
  21. template<int I, bool... Bs, typename U>
  22. struct MakeSequence<I,BoolSequence<Bs...>, U>: //not last
  23. MakeSequence<I-1, BoolSequence<Contains<U,I-1>::value,Bs...>, U>{};
  24. template<bool... Bs, typename U>
  25. struct MakeSequence<0,BoolSequence<Bs...>,U>{ //last
  26. using Type = BoolSequence<Bs...>;
  27. };
  28. template<typename T> struct BoolASCIITable;
  29. template<bool... Bs> struct BoolASCIITable<BoolSequence<Bs...>>{
  30. /* could be made constexpr but not yet supported by MSVC */
  31. bool operator()(const char c) const{
  32. static const bool table[256] = {Bs...};
  33. return table[static_cast<int>(c)];
  34. }
  35. typedef char argument_type; //so that functional functors work
  36. };
  37. using Delims = CharSequence<'.',',',' ','-','\n'>; //list your custom delimiters here
  38. using Table = BoolASCIITable<typename MakeSequence<256,BoolSequence<>,Delims>::Type>;
  39.  
  40. template<typename T_It>
  41. std::pair<T_It,T_It> getNextToken(T_It begin,T_It end){
  42. begin = std::find_if(begin,end,std::not1(Table{})); //find first non delim or end
  43. auto second = std::find_if(begin,end,Table{}); //find first delim or end
  44. return std::make_pair(begin,second);
  45. }
  46.  
  47. int main() {
  48. std::string s{"Some people, excluding those present, have been compile time constants - since puberty."};
  49. auto it = std::begin(s);
  50. auto end = std::end(s);
  51. while(it != std::end(s)){
  52. auto token = getNextToken(it,end);
  53. std::cout << std::string(token.first,token.second) << std::endl;
  54. it = token.second;
  55. }
  56. return 0;
  57. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
Some
people
excluding
those
present
have
been
compile
time
constants
since
puberty