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

Lambda example? #30

Closed erakis closed 6 years ago

erakis commented 6 years ago

Hi,

Is there a way to use lambda instead of functor for visitor ? If yes, do you have any example ?

Best regards, Martin

K-ballo commented 6 years ago

Is there a way to use lambda instead of functor for visitor ?

Yes, just pass a lambda as the visitor callable argument. Lambdas are function objects too.

If yes, do you have any example ?

eggs::variants::apply([](auto const& x) { std::cout << x; }, vs);
erakis commented 6 years ago

Thank you for your quick answer.

But now, how to do that when there multiple type ? Ex

using VariantValue = eggs::variant<bool, float, std::string>;

struct Visitor
{
    std::string operator()(const bool& t)
    {
        return std::to_string(t);
    }

    std::string operator()(const float& t)
    {
        return std::to_string(t);
    }
    std::string operator()(const std::string& t)
    {
        return t;
    }
};

VariantValue variant{ std::string("test") };
std::cout << eggs::variants::apply(visitor, variant);

How do you declare the lambda when visitor has multiple types ?

Best regards,

K-ballo commented 6 years ago

How do you declare the lambda when visitor has multiple types ?

[](auto const& t) { 
  using T = std::decay_t<decltype(t)>;
  if constexpr (std::is_same_v<T, bool>)
    return std::to_string(t);
  else if constexpr (std::is_same_v<T, float>)
    return std::to_string(t);
  else if constexpr (std::is_same_v<T, std::string>)
    return t;
}
erakis commented 6 years ago

Ahh... thank you so much, I did not think about Extended constexpr. Unfortunately, I can not use it with VS 2015 😒