如何为用户定义类型实现初始化列表? (类似于 std::vector 初始化列表)

新手上路,请多包涵

std::vector 可以初始化为

std::vector<std::string> words1 {"the", "frogurt", "is", "also", "cursed"};

参考

现在,如果想为我的一种类型实现类似的功能,我该怎么做呢?我应该如何实现这个功能的构造函数?

标准如何支持我实现这一目标(参考标准将最有帮助)?基本上,如果你能教我如何实现 std::vector 就足够了。

这也可以在 C++11 之前完成吗?

另外,我可以有一个 POD 结构类型初始化器列表,以便我可以使用不同类型的值来初始化我的类型吗?

原文由 Koushik Shetty 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 685
1 个回答

创建一个以 std::initializer_list 作为参数的构造函数:

 #include <vector>
#include <initializer_list>

template <typename T>
struct foo
{
private:
    std::vector<T> vec;

public:

    foo(std::initializer_list<T> init)
      : vec(init)
    { }
};

int main()
{
    foo<int> f {1, 2, 3, 4, 5};
}

std::vector does this is almost exactly the same way (although begin() and end() - std::initializer_list has iterators much the same way as other containers做)。从 gcc

   vector(initializer_list<value_type> __l,
     const allocator_type& __a = allocator_type())
  : _Base(__a)
  {
_M_range_initialize(__l.begin(), __l.end(),
            random_access_iterator_tag());
  }

编辑:我不是你想要做的 100%,但你可以简单地使用 统一初始化 来得到你想要的:

 struct bar
{
private:

    int i;
    double j;
    std::string k;

public:

    bar(int i_, double j_, const std::string& k_)
      : i(i_), j(j_), k(k_)
    { }

};

int main()
{
    bar b {1, 2.0, "hi"};
}

原文由 Yuushi 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题