#include <iostream>
#include <iterator>

template<class T>
class Base
{
protected:
    std::string mFoo;
    
public:
    // note: *something* virtual required for dynamic_cast
    virtual ~Base() {};
    
    T& withFoo(const std::string& foo)
    {
        mFoo = foo;
        return dynamic_cast<T&>(*this);
    }
};

class Derived : public Base<Derived>
{
protected:
    std::string mBar;
    
public:
    Derived& withBar(std::string bar)
    {
        mBar = bar;
        return *this;
    }
    
    void doOutput()
    {
        std::cout << "Foo is " << mFoo
                  << ".  Bar is " << mBar << "."
                  << std::endl;
    }
};


int main()
{
    Derived d;
    d.withFoo("foo").withBar("bar");
    d.doOutput();
    
    return 0;
}