A minimum iterator template that works with ostream_iterator


This iterator works with std::ostream_iterator to get the container’s content printed to cout.
It’s minimum because it stops working if I take one more element out.
Minimum snippets is best to show how things work under the hood.

template <class T> class CMyContainer
{
public:
	enum {MAX = 2}; //only hold two elements
protected:
    T maData[MAX];
public:
    CMyContainer<T>(const T& t1, const T& t2)
	{
		maData[0] = t1; maData[1] = t2; //pre-initialized to only 2 element
	}
    class iterator;
    iterator begin()
	{
		return iterator(0, this);
	}
    iterator end()
	{
		return iterator(MAX, this);
	}
};
template <class T> class CMyContainer<T>::iterator
{
    CMyContainer<T> * mpContainer;
    int miIndex;
public:
	typedef std::forward_iterator_tag iterator_category;
	typedef void value_type;
	typedef void difference_type;
	typedef void distance_type;
	typedef void pointer;
	typedef void reference;
    iterator () {}
    iterator (int iIndex, CMyContainer<T> * c): miIndex(iIndex), mpContainer(c) {}
    bool operator==(const iterator & z)
	{
		return miIndex == z.miIndex;
	}
    bool operator!=(const iterator & z)
	{
		return !operator==(z);
	}
    void operator++()
	{
		++ miIndex;
    }
    T& operator*()
	{
		return mpContainer->maData[miIndex];
	}
};

void TestCustomIterator()
{
	CMyContainer<int> b(1, 2);
	CMyContainer<int>::iterator it;
	ostream_iterator<int> o(cout, " ");
	copy(b.begin(), b.end(), o); //this line prints 1 2 (content of b)
}
Advertisements

What’s the default inheritance type when ‘struct’ derived from ‘class’?


Dose this piece of code compile?

class CBase
{
public:
	void b() {	}
};
struct CSub: CBase //default inheritance
{
};
void TestInheritance()
{
	CSub Sub;
	Sub.b();

}

Yes. The default inheritance is public as long as the derived is ‘struct’ regardless of base calss.

How to define a member function pointer?


Here I define a pointer pMember pointing to CMyClass::MemberFunc and use it to call the function.

struct CMyClass
{
	int MemberFunc(char c)
	{
		return c;
	};
};
void test()
{
	CMyClass MyClass;
	int (CMyClass::*pMember)(char) = &CMyClass::MemberFunc;
	int iMember = (MyClass.*pMember)(2);
}

auto keyword has changed


In Visual Studio 2010 with default compiler options,
this is ok:

auto i = 0;

But this is error.

auto int i = 0;

The library builders want it more than application developers.
So many interesting features in C++11.