1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
#include <iostream>
#include <vector>
#include <type_traits>
struct base
{
virtual ~base() = default ;
virtual std::ostream& print( std::ostream& stm = std::cout ) const { return stm << "base" ; }
};
std::ostream& operator<< ( std::ostream& stm, const base& b ) { return b.print(stm) ; }
struct derived : base
{
virtual std::ostream& print( std::ostream& stm = std::cout ) const override { return stm << "derived" ; }
};
struct composite
{
std::vector<base*> ptrs_base ;
template < typename ITERATOR >
composite( ITERATOR begin, ITERATOR end,
std::enable_if< std::is_convertible< typename std::iterator_traits<ITERATOR>::value_type, base* >::value >* = nullptr )
: ptrs_base(begin,end) {}
template < typename T >
composite( T** pp, std::size_t n, std::enable_if< std::is_convertible< T*, base* >::value >* = nullptr )
: ptrs_base( pp, pp+n ) {}
void print( std::ostream& stm = std::cout ) const { for( auto p : ptrs_base ) if(p) stm << *p << '\n' ; }
};
int main()
{
derived d1, d2, d3 ;
derived* ptrs_derived[3] { std::addressof(d1), std::addressof(d2), std::addressof(d3) } ;
composite c( std::begin(ptrs_derived), std::end(ptrs_derived) ) ;
c.print() ;
composite c2( ptrs_derived, 3 ) ;
c2.print() ;
}
|