gpt4 book ai didi

c++ - 在 vector 上使用 is_copy_constructible 误报

转载 作者:IT老高 更新时间:2023-10-28 22:59:27 25 4
gpt4 key购买 nike

类型 trait 是否应该能够处理 std::vector < std::unique_ptr <int> > 之类的情况?并检测到它不是可复制的?

这是 https://ideone.com/gbcRUa 的示例(运行 g++ 4.8.1)

#include <type_traits>
#include <vector>
#include <iostream>
#include <memory>

int main()
{
// This prints 1, implying that it's copy constructible, when it's clearly not
std::cout << std::is_copy_constructible< std::vector<std::unique_ptr<int> > >::value << std::endl;
return 0;
}

如果这是 is_copy_constructible 的正确行为,有没有办法检测到复制结构是不正确的?好吧,不仅仅是让它无法编译。

最佳答案

这是因为 std::vector 的设计存在缺陷。 . std::vector定义复制构造,即使它无法编译,并且依赖于 std::vector 的用户如果编译失败则不调用该方法。

如果类型包含在 vector 中,则另一种设计是 SFINAE 阻止方法的调用。没有复制构造函数。但是,std::vector是在现代 SFINAE 技术开发之前设计的。

它可能会被重新安装到新的 C++ 迭代中,因为很少有代码会被破坏。不能说没有代码会破坏,因为您可以拥有依赖于 std::is_copy_constructible< std::vector< no_copy_type > > 事实的代码。是 std::true_type , 或等效表达式,但这是一个非常奇怪的依赖关系。

除此之外,std::vector比可以解决此问题的 SFINAE 技术更早,使用 SFINAE 这样做非常困惑(因为 SFINAE 是一种困惑的技术)。为 C++1y 提出的新概念精简版可能会使其更简洁,并且更容易包含在该语言的新迭代中。

当我有一个容器需要知道是否可以安全地复制、比较和排序包含的对象时,我的工作是专门针对 std::vector在自定义特征类上,并依赖于包含类型上的自定义特征类的值。这是一个拼凑而成的解决方案,而且非常具有侵入性。

template<template<typename>class test, typename T>
struct smart_test : test<T> {};
template<template<typename>class test, typename T, typename A>
struct smart_test<test, std::vector<T,A>> : smart_test<T> {};

这给了我们:

template<typename T>
using smart_is_copy_constructible = smart_test< std::is_copy_constructible, T >;

< 类似和 == .当我遇到更多应该将它们的属性真正转发到它们的数据的容器类型时,我可以添加更多的特化,或者我可以编写一个更高级的 SFINAE 容器测试和特征并提取基础值类型并将问题分发给测试关于值类型。

但根据我的经验,我最终会在 std::vector 上进行这些测试。 .

请注意,由于 vector 添加了“参与重载解决”规则,这是“做 SFINAE”测试的标准。

关于c++ - 在 vector <unique_ptr> 上使用 is_copy_constructible 误报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18404108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com