Is it possible to emplace a non copyable, non moveable into a std::variant

111 Views Asked by At

See

https://godbolt.org/z/Pv8xfeE17

fails

#include <iostream>
#include <variant>
#include <vector>

struct T {
    int _x;
    T(int x) : _x(x) { std::cout << "constructed" << std::endl; }
    #if 0
        T(const T& t) : _x(t._x) { std::cout << "copied" << std::endl; }
        T( T&& t) : _x(t._x) { std::cout << "moved" << std::endl; }
    #else
        T(const T& t) = delete;
        T(T&& t) = delete;
    #endif

};


T make_t(){
    return T(1);
}

int main() {

    std::variant<std::monostate,T> v;
    v.emplace<T>(make_t());
}

passes

#include <iostream>
#include <variant>
#include <vector>

struct T {
    int _x;
    T(int x) : _x(x) { std::cout << "constructed" << std::endl; }
    #if 1
        T(const T& t) : _x(t._x) { std::cout << "copied" << std::endl; }
        T(const T&& t) : _x(t._x) { std::cout << "moved" << std::endl; }
    #else
        T(const T& t) = delete;
        T(const T&& t) = delete;
    #endif

};


T make_t(){
    return T(1);
}

int main() {

    std::variant<std::monostate,T> v;
    v.emplace<T>(make_t());
}
1

There are 1 best solutions below

1
Jarod42 On

You need v.emplace<T>(1);

Demo