简体   繁体   中英

Check empty vector in initializer list

I would like initialize base class by a first item form a vector which contains base classes, eg:

struct Base { ... };

struct Derived : public Base
{
   Derived(const Base& baseClass)
      : Base(baseClass)
   {
   }
   Derived(const std::vector<Base*>& listOfBaseClass)
      : Base(*(listOfBaseClass[0]))
   {
   }
};

This solution fails when listOfBaseClass vector will be empty. How can prevent this situation. This is simplified example, so calling base class constructor like this:

std::vector<Base> baseClasses;

if(!baseClasses.empty())
{
  Derived myDerived(baseClasses[0]);
}

it is not solution for my problem. Thanks in advance.

Throw an exception if the list is empty:

 : Base(listOfBaseClass.empty() 
          ? throw std::invalid_argument("Missing base class")
          : *(listOfBaseClass[0])
        )

Non-exception variant by request:

 : Base(( (listOfBaseClass.empty() && exit(0)),
          *(listOfBaseClass[0])
       ))
Derived(const std::vector<Base*>& listOfBaseClass)
      : Base(*(listOfBaseClass->at(0)))
   {
   }

"at" provides exception safety. It throws out_of_range if n is out of bounds.

http://www.cplusplus.com/reference/vector/vector/at/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM