使用初始化程序列表初始化成员数组的正确方法是什么? [英] What's the correct way to initialize a member array with an initializer list?

查看:3287
本文介绍了使用初始化程序列表初始化成员数组的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 struct ,它保存一个数组,我想传递一个初始化列表到结构的构造函数,转发到数组。为了说明,我尝试:

I have a struct that holds an array, and I'd like to pass an initializer list to the struct's constructor to be forwarded on to the array. To illustrate, I tried:

#include <initializer_list>

struct Vector
{
    float v[3];

    Vector(std::initializer_list<float> values) : v{values} {}
};

int main()
{
    Vector v = {1, 2, 3};
}

导致错误


错误:无法转换'std :: initializer_list< float& 'to'float'in initialization

v 我尝试使用括号而不是括号,但是出现错误:

I tried using parentheses instead of braces for v but that gave the error:


错误:将'std :: initializer_list< float>'指派给'float [3]'时不兼容类型

我尝试这样做的主要动机是避免clang生成的以下警告:

My main motivation for trying to do this is to avoid the following warning that clang generates:

template <int N>
struct Vector
{
    float v[N];
};

template <>
struct Vector<2>
{
    float x, y;
};

int main()
{
    Vector<2> v2 = {1.0f, 2.0f};         // Yay, works
    Vector<3> v3 = {1.0f, 2.0f, 3.0f};   // Results in warning in clang++
    Vector<3> u3 = {{1.0f, 2.0f, 3.0f}}; // Must use two braces to avoid warning
    // If I could make Vector<N> take an initializer list in its constructor, I
    // could forward that on to the member array and avoid using the double braces
}




警告:建议大括号初始化subobject

所以我的问题是:如何用初始化列表初始化成员数组? (如何使第一个代码工作?或者是不可能的?

So my question is: How can I initialize a member array with an initializer list? (i.e. How can I make the first code work? Or is it not possible?

推荐答案

汇总,您可以使用语法

template < std::size_t len >
struct Vector
{
    float elems[len];
};

Vector<3> v = {1.0f, 2.0f, 3.0f};

注意:这是可能的,由于支架 - 无需 v = {{1,2,3}}; 虽然这也是可能的。因为更清晰和更不易出错的语法是双括号(一个用于初始化 v ,另一个用于初始化子聚合 elems )。

Note: this is possible due to brace-elision. No need for v = {{1,2,3}}; though this is also possible. Clang issues this warning because the clearer and less error-prone syntax is with the double braces (one for initializing v and one for initializing the sub-aggregate elems).

如果您的类不是聚合,您可以使用可变参数模板:

If your class is not an aggregate, you can use variadic templates:

#include <array>
#include <cstddef>

template < std::size_t len >
struct Vector
{
    std::array < float, len > m;  // also works with raw array `float m[len];`

    template < typename... TT >
    Vector(TT... pp) : m{{pp...}}
    {}

    // better, using perfect forwarding:
    // template < typename... TT >
    // Vector(TT&&... pp) : m{{std::forward<TT>(pp)...}}
    // {}
};

Vector<3> a = {1.0f, 2.0f, 3.0f};

这篇关于使用初始化程序列表初始化成员数组的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆