I'm trying to create objects of this class, but storage duration should be static: The program must create exactly storage_count (not more, not less) objects of type anywhere, one after another, starting from index argument value 0, and progressing up to and including storage_count - 1.
class anywhere
{
public:
anywhere( std::string storage_duration_name, unsigned short index )
: storage_duration_name_( std::move( storage_duration_name )), index_( index )
{
std::cout << "constructor " << storage_duration_name_ << ' ' << index_ << std::endl;
}
~anywhere( )
{ std::cout << "destructor " << storage_duration_name_ << ' ' << index_ << std::endl; }
private:
const std::string storage_duration_name_;
const unsigned short index_;
anywhere( const anywhere & ) = delete;
anywhere( anywhere && ) = delete;
};
The problem here is that count of objects are determined at run time and may vary 0 <= count <=100. As it is impossible to create static objects of class inside of a loop(it won't create them every time, only on first iteration it is created) or recursively (which gives undefined behavior). I tried something like this but I think there may be short way of doing this.
//form main() ...
unsigned short storage_count = argv[ 2 ];//with checks focourse
unsigned short number = 0;
object_creator<anywhere>( storage_duration_name, number, storage_count );
//end of main() ...
template<class T>
void object_creator( std::string &storage, unsigned short current, unsigned short &num )
{
if ( storage == "static" )
{
if ( current > num )
{
return;
} else if ( current == 1 )
{
static T o1 = T( storage, 0 );
object_creator<anywhere>( storage, ++current, num );
} else if ( current == 2 )
{
static T o2 = T( storage, 1 );
object_creator<anywhere>( storage, ++current, num );
} else if ( current == 3 )
{
static T o3 = T( storage, 2 );
object_creator<anywhere>( storage, ++current, num );
} else if ( current == 4 )
{
static T o4 = T( storage, 3 );
object_creator<anywhere>( storage, ++current, num );
//..... for 100 of them
Any hints or sources to read I'll appreciate that!