gpt4 book ai didi

c++ - 为什么不能用兼容类型的 std::tuple 按元素构造 std::tuple?

转载 作者:可可西里 更新时间:2023-11-01 15:25:07 36 4
gpt4 key购买 nike

我无法初始化 std::tuple来自 std::tuple 的逐元素元素兼容类型。为什么它不像 boost::tuple 那样工作?

#include <tuple>
#include <boost/tuple/tuple.hpp>

template <typename T>
struct Foo
{
// error: cannot convert 'std::tuple<int>' to 'int' in initialization
template <typename U>
Foo(U &&u) : val(std::forward<U>(u)) {}

T val;
};

int main()
{
boost::tuple<Foo<int>>{boost::tuple<int>{}}; // ok

auto a = boost::tuple<int>{};
boost::tuple<Foo<int>>{a}; // ok

std::tuple<Foo<int>>{std::tuple<int>{}}; // fails with rvalue

auto b = std::tuple<int>{};
std::tuple<Foo<int>>{b}; // fails with lvalue
}

Live on Coliru (GCC 或 Clang 和 libstdc++ 不编译,但是 Clang 和 libc++ 编译没有错误)


std::tuple不进行逐元素构造,它实例化 Foo<int>::Foo<std::tuple<int>>而不是 Foo<int>::Foo<int> .我以为 std::tuple::tuple overloads no. 4 and 5正是为了这个目的:

template <class... UTypes>
tuple(const tuple<UTypes...>& other);

template <class... UTypes>
tuple(tuple<UTypes...>&& other);

注意:

Does not participate in overload resolution unless
std::is_constructible<Ti, const Ui&>::value is true for all i.

std::is_constructible<Foo<int>, int>::valuetrue .从 GCC 模板错误中,我可以看到没有重载。 3:

template <class... UTypes>
explicit tuple(UTypes&&... args);

被选中。为什么?

最佳答案

当传递 tuple& 时,重载 (4) 和 (5) 比 (3) 更差:它们是 const&&& 重载, 而 (3) 通过完美转发的魔力完全匹配。

(3) 是有效的,因为您的 Foo(U&&) 构造函数过于贪婪。

将 SFINAE 检查添加到 Foo(U&&) 以便它在构建失败时无法匹配:

template <class U,
std::enable_if_t<std::is_convertible<U,int>{},int>* =nullptr
>
Foo(U &&u) : val(std::forward<U>(u)) {}

但是,右值大小写应该有效或不明确。查看您的实时示例的错误日志,我看到的唯一错误是左值错误。

关于c++ - 为什么不能用兼容类型的 std::tuple 按元素构造 std::tuple?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38281724/

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