Getter for boost :: variant object

I have a getter object that returns an object of type Type, which is defined as follows:

typedef boost::variant<int, std::string> Empty; 

It often happens that I will have neither an int nor a string to return, and you will have to return an empty state instead. Do you think I will return this state?

a) typedef is an empty type and add it to the variant: boost::variant<int, std::string, Empty> .

b) return Type ()

c) Make an exception

d) returns boost :: shared_ptr, which points to NULL if empty.

+4
source share
3 answers

The correct answer is to use boost::blank for an option that cannot have anything in it. So your typedef variant looks like this:

 typedef boost::variant<boost::blank, int, std::string> Empty; 

blank designed specifically for this, and variant has a special code based on it. Using it, you get a guarantee of no memory when copying (if the participants do not allocate a copy). So good.

Since your option may be "empty", it is important that all your processing visitors can process it. Most often it’s more convenient to add an additional visitor path than to have several conditional expressions based on optional or something else. Different code paths will be localized to visitors, which often makes more sense than optional<variant> .

+8
source

Wrap it in boost::optional , it has a simple test (convertible to logical) to determine if a valid value exists - then you do not need to pollute your version with an "empty" state. eg.

 boost::optional<boost::variant<... > > some_func() { : } 

Remember to use the built-in function in your function when you really need to return something.

+3
source

This is a general approach, if it is likely that a method cannot return an object, make the method return bool:

 bool get_value(Type& type) { if ( /*check variant emptyness*/) // one can use this - http://stackoverflow.com/a/7668530/670719 return false; // else assign type } 

Comments on your decisions:

a) if you return Empty, you still have to do a check after calling the method. So why add more types if you already have a built-in bool.

b) Type () may have the same meaning as the legal variable

c) The exception is something exceptional, but from your description "often"

d) your problem is that you cannot use Type and at the same time you cannot return boost :: variant, so adding another type with additional problems with the owners raises more questions about what happens without solving the initial problem clean interface.

+1
source

Source: https://habr.com/ru/post/1438353/


All Articles