我最近阅读了这篇博文,了解为什么向量必须是无条件可复制的,以便它可以支持不完整的类型。我知道从逻辑的角度来看这也是必要的,因为以下内容对可复制性具有循环依赖性:
struct Test {
std::vector<Test> v;
};
Run Code Online (Sandbox Code Playgroud)
现在我想,是否至少可以尝试提供现有的最佳信息。换句话说,std::vector<T>当且仅当复制可T构造或不完整时,才可复制构造。因此std::vector<std::unique_ptr<T>>永远不会被复制构造,因为std::unique_vector它是仅移动的,独立于T.
我得出以下解决方案:
#include <type_traits>
#include <memory>
template<class T, class = decltype(sizeof(int))>
struct is_complete : std::false_type {};
template<class T>
struct is_complete<T, decltype(sizeof(T))> : std::true_type{};
template<class T>
constexpr bool is_complete_v = is_complete<T>::value;
// Indirection to avoid instantiation of is_copy_constructible with incomplete type
template<class T, class = std::enable_if_t<is_complete_v<T>>>
struct copyable {
static constexpr bool value = std::is_copy_constructible_v<T>;
};
template<class T>
struct copyable<T, void> : …Run Code Online (Sandbox Code Playgroud)