boost::variant; std::unique_ptr and copy

后端 未结 2 1156
温柔的废话
温柔的废话 2021-01-05 04:46

This Question Determined That a Non-Copyable Type Can\'t Be Used With Boost Variant

Tree class

template 

        
相关标签:
2条回答
  • 2021-01-05 05:10
    using Mixed = boost::variant< 
      std::unique_ptr<char>,
      std::unique_ptr<short>,
      std::unique_ptr<int>,
      std::unique_ptr<unsigned long>
    >;
    
    int main() {    
      auto md = std::unique_ptr<int>(new int(123));
      Mixed mixed = std::move(md);
      std::cout << *boost::get< std::unique_ptr<int> >(mixed) << std::endl;
      return 0;
    }
    

    unique_ptr is move-only and can be used in variant. The above example can compile and work (C++11).

    0 讨论(0)
  • 2021-01-05 05:35

    Concerning the call to boost::bind(), you should use boost::ref() when passing an object by reference to a function template that accepts the corresponding argument by value, otherwise a copy will be attempted (which results in a compiler error in this case, since the copy constructor is inaccessible):

    boost::bind(TreeVisitor(), boost::ref(tree), val, keyIndex);
    //                         ^^^^^^^^^^^^^^^^
    

    However, there is a bigger problem here: boost::variant can only hold types which are copy-constructible. From the Boost.Variant online documentation:

    The requirements on a bounded type are as follows:

    • CopyConstructible [20.1.3].

    • Destructor upholds the no-throw exception-safety guarantee.

    • Complete at the point of variant template instantiation. (See boost::recursive_wrapper<T> for a type wrapper that accepts incomplete types to enable recursive variant types.)

    Every type specified as a template argument to variant must at minimum fulfill the above requirements. [...]

    0 讨论(0)
提交回复
热议问题