mapbox / variant

C++11/C++14 Variant
BSD 3-Clause "New" or "Revised" License
371 stars 100 forks source link

Add move semantics to make_visitor and visitor #154

Closed ricardocosme closed 7 years ago

ricardocosme commented 7 years ago

Hi,

This pull request adds move semantics support to avoid unnecessary internal copies of closures passed to make_visitor and it permits the usage of init capture(feature of C++14) to use movable-only types. It also adds a test case for lambda with init capture and movable(but not copyable) object.

Before this:

struct movable_and_copyable
{
    movable_and_copyable() = default;
    movable_and_copyable(movable_and_copyable&&)
    { std::cout << "move ctor" << std::endl; }
    movable_and_copyable(const movable_and_copyable&) 
    { std::cout << "copy ctor" << std::endl; }
};

struct movable_only
{
    movable_only() = default;
    movable_only(movable_only&&) = default;
};

int main()
{
    mapbox::util::variant<int, double> variant;
    movable_and_copyable obj;
    variant.match([obj](auto&&){});

    // This legal C++14 code doesn't compile.
    // movable_only movable_only_obj;
    // variant.match([p = std::move(movable_only_obj)](auto&&){});
}

Output:

copy ctor
move ctor
copy ctor
copy ctor
jfirebaugh commented 7 years ago

Over to @artemp for the merge.

artemp commented 7 years ago

👍