fork download
  1. #include <iostream>
  2. #include <iterator>
  3.  
  4. template<class T>
  5. class Base
  6. {
  7. protected:
  8. std::string mFoo;
  9.  
  10. public:
  11. // note: *something* virtual required for dynamic_cast
  12. virtual ~Base() {};
  13.  
  14. T& withFoo(const std::string& foo)
  15. {
  16. mFoo = foo;
  17. return dynamic_cast<T&>(*this);
  18. }
  19. };
  20.  
  21. class Derived : public Base<Derived>
  22. {
  23. protected:
  24. std::string mBar;
  25.  
  26. public:
  27. Derived& withBar(std::string bar)
  28. {
  29. mBar = bar;
  30. return *this;
  31. }
  32.  
  33. void doOutput()
  34. {
  35. std::cout << "Foo is " << mFoo
  36. << ". Bar is " << mBar << "."
  37. << std::endl;
  38. }
  39. };
  40.  
  41.  
  42. int main()
  43. {
  44. Derived d;
  45. d.withFoo("foo").withBar("bar");
  46. d.doOutput();
  47.  
  48. return 0;
  49. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
Foo is foo.  Bar is bar.