code_junkie

Why should I ever use inline code?

Nov 11th, 2011
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. #define unsafe(i) ( (i) >= 0 ? (i) : -(i) )
  2.  
  3. [...]
  4. unsafe(x++); // x is incremented twice!
  5. unsafe(f()); // f() is called twice!
  6. [...]
  7.  
  8. // header.hpp
  9. #include <iosfwd> // for std::ostream&
  10.  
  11. #ifndef HEADER_HPP
  12. #define HEADER_HPP
  13.  
  14. template <typename IteratorT>
  15. /*inline*/ void print_all(IteratorT begin, IteratorT end, std::ostream& out, char sep = ' ') {
  16. while (begin != end)
  17. out << *begin++ << sep;
  18. }
  19.  
  20. #endif // !defined(HEADER_HPP)
  21.  
  22. // test.cpp
  23. #include <iostream>
  24. #include <vector>
  25. #include "header.hpp"
  26.  
  27. void test_function() {
  28. using namespace std;
  29. vector<int> vec;
  30. int x;
  31. while (cin >> x) vec.push_back(x);
  32. cout << "Results: ";
  33. print_all(vec.begin(), vec.end());
  34. cout << endl;
  35. }
  36.  
  37. // main.cpp
  38. #include <iostream>
  39. #include <vector>
  40. #include "header.hpp"
  41.  
  42. void test_function(); // Forward declaration.
  43.  
  44. int main() {
  45. using namespace std;
  46. vector<int> xyz(23, 42);
  47. print_all(xyz);
  48. cout << endl << "Test call:" << endl;
  49. test_function();
  50. }
  51.  
  52. $ g++ -Wall -pedantic main.cpp test.cpp
  53.  
  54. CPoint
  55. {
  56. public:
  57.  
  58. inline int x() const { return m_x ; }
  59. inline int y() const { return m_y ; }
  60.  
  61. private:
  62. int m_x ;
  63. int m_y ;
  64.  
  65. };
Add Comment
Please, Sign In to add comment