从构造函数中的初始化列表推断成员大小(CWG 1591)什么是正确的方法?

问题描述 投票:0回答:1

我有一个类

Vec<C>
,其工作方式如下,我需要知道一种编写构造函数和/或推导指南 的方法,以便用大括号括起来的初始值设定项列表将
C
推导为
std::array<T,N>

它当然可以与

std::vector<T>
一起使用,因为不需要知道尺寸。

#include <cassert>
#include <iostream>
#include <array>
#include <vector>
#include <concepts>
#include <type_traits>

template<typename T>
concept has_resize = requires(T t)
{
    {t.resize(0)};
};

template<typename C>
class Vec
{
    C elems;
public:
    template<typename IndexType> 
    requires std::integral<IndexType> && std::is_unsigned_v<IndexType>
    auto operator[](IndexType i) const 
    { 
         return elems[i];
    }
    auto size()               const { return elems.size(); }
    template<typename T>
    Vec(std::initializer_list<T> init)//MEMBER INITIALIZER LIST?
    {
        // WHAT CODE GOES HERE?
    }
    Vec(auto init)
    {
        if constexpr (has_resize<decltype(elems)>) 
            elems.resize(init.size());
        for (decltype(init.size()) i = 0; i<init.size() ; i++)
            elems[i] = init[i];
    }
};

template<typename C>
Vec(C) -> Vec<C>;

//WHAT'S THE CORRECT DEDUCTION GUIDE?

int main()
{
    Vec v0({1, 4, 7});
    Vec v1(std::array<int,3>{2, 5, 8});
    Vec v2(std::vector<double>{3, 6, 9});
}

编辑1:我们的想法不是修改调用

Vec v0({1, 4, 7});
Vec v0{1, 4, 7};
当然。

编辑2:

template<typename T> Vec(const std::initializer_list<T>& vec) -> Vec<std::array<T, vec.size()>>;
不起作用,如下所示:https://godbolt.org/z/b5vno6ff8

c++ overloading constructor-overloading deduction-guide
1个回答
0
投票

要从大括号括起来的列表中推断长度,您需要使用对数组的引用。语法有点奇怪:

template<class T, std::size_t N>
Vec(T (&&init)[N]) -> Vec<std::array<T, N>>;
© www.soinside.com 2019 - 2024. All rights reserved.