eggs-cpp / variant

Eggs.Variant is a C++11/14/17 generic, type-safe, discriminated union.
http://eggs-cpp.github.io/variant/
Boost Software License 1.0
138 stars 27 forks source link

Implement get_if overloads (was: No compile error with invalid call to target) #27

Closed jcelerier closed 7 years ago

jcelerier commented 7 years ago

Hello:

The compiler happily accepts the following code:

#include <eggs/variant.hpp>
#include <string>
int main()
{
  eggs::variant<int, bool> foo;
  foo.target<std::string>();
}

couldn't it be made so that target<T> only compiles if the variant actually has a T type ?

K-ballo commented 7 years ago

This is by design, as variant::target models a poor man's dynamic_cast:

#include <string>
struct variant { virtual ~variant(){} };
int main()
{
  variant foo;
  dynamic_cast<std::string*>(&foo); // no error
}

It could certainly be changed, but what would the motivation be? What's the rationale for not using the value access functions instead? Would this use case be better served by a get_if, like the one the standard library has?

jcelerier commented 7 years ago

Would this use case be better served by a get_if, like the one the standard library has?

Yes, I did not know about get_if but this is the behaviour I am looking for (https://godbolt.org/g/tjdW31).

viboes commented 7 years ago

get_if template parameter must be one of the alternatives

http://en.cppreference.com/w/cpp/utility/variant/get_if

K-ballo commented 7 years ago

I have just pushed the implementation of get_if overloads to the develop branch. The current wording does not guarantee them to be ill-formed for invalid calls, but the implementation does require it; as a result, the compilation errors can be quite poor.

Adding ill-formed guarantees for variant_element, get, and get_if comes next. I will take this opportunity to go over the API and check that all SFINAE conditions are checked for, and all ill-formed conditions yield a decent, static_assert-based, error message.

K-ballo commented 7 years ago

Ill-formed guarantees and decent error messages are now in the develop branch. Will close this issue once they are merged to the master branch.

jcelerier commented 7 years ago

thank you very much !