【问题标题】:std::make_from_tuple doesn't compile without constructorstd::make_from_tuple 在没有构造函数的情况下无法编译
【发布时间】:2021-12-29 09:17:12
【问题描述】:

我有一个简单的结构:

struct A
{
    int a;
    int b;
    int c;
    
    // A(int a, int b, int c) : a{a}, b{b}, c{c} { }
};

现在对构造函数进行注释。我正在尝试以这种方式创建A 类型的对象:

auto t = std::make_tuple(1, 2, 3);
A a = std::make_from_tuple<A>(std::move(t));

但它不会编译。 MSVC 给出一条消息: &lt;function-style-cast&gt;: cannot convert from initializer_list to _Ty。 在我取消注释 struct A 的构造函数后,它开始工作。

问题是:为什么std::make_from_tuple() 需要用户定义的构造函数而不是默认构造函数?

【问题讨论】:

    标签: c++ tuples c++17 default-constructor


    【解决方案1】:

    如果你仔细看看make_from_tuplestandard中的实现:

    namespace std {
      template<class T, class Tuple, size_t... I>
        requires is_constructible_v<T, decltype(get<I>(declval<Tuple>()))...>
      constexpr T make-from-tuple-impl(Tuple&& t, index_sequence<I...>) {   
        return T(get<I>(std::forward<Tuple>(t))...);
      }
    }
    

    它使用括号(())通过直接初始化来初始化T。由于A是一个聚合,所以在C++17中不能使用括号进行初始化,只能使用花括号({})进行列表初始化。

    值得注意的是,P0960 使得在 C++20 中使用括号初始化聚合成为可能,因此您的代码在 C++20 中为 well-formed

    【讨论】:

      猜你喜欢
      • 2013-06-07
      • 2017-04-11
      • 1970-01-01
      • 2015-11-17
      • 2021-07-28
      • 1970-01-01
      • 2020-12-30
      • 2016-06-01
      • 1970-01-01
      相关资源
      最近更新 更多