explicit_cast.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * Simple test file for cxxomfort
  3. * When compiled and run, this will show
  4. * how to use explicit_cast<>.
  5. *
  6. * This and other examples assume cxxomfort is installed in
  7. * include library path; if otherwise, compile with
  8. * -I /path/to/cxxomfort .
  9. */
  10. #include <cxxomfort/base.hpp>
  11. #include <cxxomfort/string.hpp>
  12. #include <iostream>
  13. #include <string>
  14. struct mybar {
  15. mybar (int x)
  16. : v(x) {++z;}
  17. int v;
  18. static int z;
  19. };
  20. int mybar::z= 0;
  21. struct myfoo {
  22. myfoo (unsigned x) : foo(x) {}
  23. CXXO_EXPLICIT_OPERATOR(bool) () const {
  24. bool b = true;
  25. return b;
  26. }
  27. CXXO_EXPLICIT_OPERATOR(std::string) () const {
  28. return std::string(foo, 'x');
  29. }
  30. CXXO_EXPLICIT_OPERATOR(mybar) () const {
  31. return mybar(static_cast<int>(foo));
  32. }
  33. private:
  34. unsigned foo;
  35. };
  36. void dobar (mybar const& b) {
  37. using namespace std;
  38. cout<< b.v<< ","<< b.z<< endl;
  39. }
  40. int doint (myfoo const& f) {
  41. return explicit_cast<bool>(f);
  42. }
  43. int main () {
  44. using namespace std;
  45. cxxomfort::output_info(); cout<< endl;
  46. myfoo foo1(4);
  47. myfoo foo2(7);
  48. mybar bar1(2);
  49. mybar bar2(4);
  50. //long z1 = explicit_cast<bool>(foo2); (void)z1; // should not compile since we only want explicit things
  51. //long z2 = static_cast<bool>(foo2); (void)z2; // this works only in C++11
  52. cout<< "Should show "<< bar1.v<< ",x :"<< endl;
  53. dobar(bar1);
  54. cout<< "Should show "<< bar2.v<< ",x :"<< endl;
  55. dobar(bar2);
  56. cout<< "Should show an integer: "
  57. << doint(foo2)<< endl;
  58. //dobar(foo2); // <-- should fail
  59. cout<< "Should show the var of foo2:"<< endl;
  60. dobar( explicit_cast<mybar>(foo2)); // <-- should work
  61. string str0 = "0";
  62. cout<< str0<< endl;
  63. string str1 = explicit_cast<string>(foo1);
  64. //string str2 = foo1; // <-- should fail
  65. cout<< str1<< endl;
  66. }