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 45 46 47 48 49 50
|
#include <iostream>
#include <string>
#include <iomanip>
#include <iterator>
template < typename T > struct node
{
node() = default ;
/* explicit */ node( const T& value, node* next = nullptr ) : value(value), next(next) {}
/* explicit */ node( T&& value, node* next = nullptr ) : value( std::move(value) ), next(next) {}
T value {} ;
node* next = nullptr ;
};
int main()
{
constexpr std::size_t N = 10 ;
{
// last four elements are value initialised (zero initialised)
node<int> nodes[N] { {12}, {15}, {67}, {89}, {32}, {45} } ;
for( auto p = nodes ; p != nodes+N-1 ; ++p ) p->next = p+1 ;
for( auto lst = nodes ; lst ; lst = lst->next ) std::cout << lst->value << ' ' ;
std::cout << '\n' ;
}
{
// last four elements are value initialised (default constructed)
node<std::string> nodes[N] { {"abc"}, {"de"}, {"fghij"}, {"k"}, {"lmnop"}, {"qrstuvwxyz"} } ;
for( auto p = nodes ; p != nodes+N-1 ; ++p ) p->next = p+1 ;
for( auto lst = nodes ; lst ; lst = lst->next ) std::cout << std::quoted(lst->value) << ' ' ;
std::cout << '\n' ;
}
{
struct A { std::string str ; A( std::string str ) : str(str) {} };
// node<A> nodes[N] { {{"abc"}}, {{"de"}}, {{"fghij"}}, {{"k"}}, {{"lmnop"}}, {{"qrstuvwxyz"}} } ;
// *** error: A is not DefaultConstructible
node<A> nodes[] { {{"abc"}}, {{"de"}}, {{"fghij"}}, {{"k"}}, {{"lmnop"}}, {{"qrstuvwxyz"}} } ;
for( auto p = std::begin(nodes) ; p != std::end(nodes)-1 ; ++p ) p->next = p+1 ;
for( auto lst = std::begin(nodes) ; lst ; lst = lst->next ) std::cout << std::quoted(lst->value.str) << ' ' ;
std::cout << '\n' ;
}
}
|