Re: Linked list of references
This is still buggy in VC++-10.0/Release (not debug)
#include
<iostream>
template<typename T> struct head_holder
{
explicit head_holder(T& t) : head_( &t ){}
T& head()
const{ return (*this->head_); }
private:
T* head_;
};
template<typename T>
struct tail_holder
{
tail_holder(T const& t) : tail_( t ){}
typedef T const& result_type;
T const& tail()const{ return this->tail_; }
private:
T const tail_; // notice value
};
template<typename T, typename H>
struct list1;
template<typename H>
struct list0
: head_holder<H>
{
list0(H& x)
:head_holder<H>( x )
{}
template<typename U>
list1<list0, U>
operator()(U& y)const
{
return list1<list0, U>(*this, y);
}
template<typename U>
list1<list0, U
const> operator()(U const& y)const
{
return list1<list0, U const>(*this, y);
}
};
template<typename T, typename H>
struct list2;
template<typename T, typename H>
struct list1
:
tail_holder<T>,
head_holder<H>
{
list1(T t, H& y)
:tail_holder<T>( t )
, head_holder<H>( y )
{}
template<typename U>
list2<list1, U>
operator()(U& z)const{
return list2<list1, U>(*this, z);
}
template<typename U>
list2<list1, U
const> operator()(U const& z)const{
return list2<list1, U const>(*this, z);
}
};
template<typename T, typename H>
struct list2
:
tail_holder<T>,
head_holder<H>
{
list2(T t, H& y)
:tail_holder<T>( t )
,head_holder<H>( y )
{}
};
template<typename T>
list0<T> make( T& x ){
return list0<T>( x ); }
template<typename T>
list0<T
const> make( T const& x ){ return list0<T const>( x ); }
int
main()
{
int x = -1, y = 2, z = -3;
{
std::cout <<
"lvalue" << std::endl;
typedef int T;
list2<list1<list0<T>, T>, T > l2 = list0<T>( x )( y )( z );
if( &l2.head() != &z ){ std::cout << l2.head() << ' '; }
if( &l2.tail().head() != &y ){ std::cout << l2.tail().head() << ' '; }
if( &l2.tail().tail().head() != &x ){ std::cout <<
l2.tail().tail().head(); }
std::cout << std::endl;
}
{
std::cout <<
"rvalue" << std::endl;
typedef int const T;
list2<list1<list0<T>, T>, T> l2 = list0<T>( -1 )( 2 )( -3 );
if( l2.head() != -3 ){ std::cout << l2.head() << ' '; }
if( l2.tail().head() != 2 ){ std::cout << l2.tail().head() << ' '; }
if( l2.tail().tail().head() != -1 ){ std::cout <<
l2.tail().tail().head(); }
std::cout << std::endl;
}
return 0;
}
// outputs lvalue rvalue -3 -3
// should output lvalue rvalue