C++0x 嵌套初始值设定项列表
我想使用 C++0x 新的初始值设定项列表功能来初始化 std::vector,其中包含我当前正在开发的新 API 的编译时定义的项目数。像这样的事情:
template<int n>
std::initializer_list<std::string> duplicate(std::string s) {
// return s duplicated n times
return { s, s, s };
}
std::vector<std::string> v = { "foo", duplicate<3>("bar") };
你知道如何实现这个目标吗?有可能吗?我知道我需要使用 TMP 和递归来构建重复字符串列表,并最终通过常量(例如枚举)以某种方式访问它。但似乎我什至无法像这样嵌套初始化列表。
I would like to use C++0x new initializer list feature to initialize a std::vector with a compile time defined number of items for a new API I'm currently working on. Something like this:
template<int n>
std::initializer_list<std::string> duplicate(std::string s) {
// return s duplicated n times
return { s, s, s };
}
std::vector<std::string> v = { "foo", duplicate<3>("bar") };
Do you have any idea how to accomplish this? Is it even possible? I'm aware of that I will need to use TMP and recursion to build up the list of duplicated strings and finally access it somehow through a constant (e.g., enum). But it seems that I cannot even nest the initializer list like this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能嵌套初始值设定项列表来扩展它们,也不能添加/连接它们。它们只是访问编译时大小的数组的一些语法糖。即使复制initializer_lists也不会复制它们的项目。最重要的是,这意味着您不能使用重复的返回值!根据 N3290 中的 8.5.4p6,函数返回时引用的数组将被销毁:
(在 return 语句中创建临时值,然后按值返回。即使发生复制省略,复制的所有其他语义也不会改变。)
例如,与此处创建的临时初始值设定项列表进行比较,然后将其传递给 ctor 和在对象初始化后销毁,同时同一完整表达式中的所有其他临时对象(如果有的话)都将被销毁:
不要操作初始值设定项列表,而是使用向量的方法插入 N 个副本:
You cannot nest initializer lists in order to extend them, nor can you add/concatenate them. They are only a bit of syntactic sugar to access a compile-time-sized array. Even copying initializer_lists doesn't copy their items. Most importantly, this means you cannot use the return value of duplicate! The referenced array is destroyed when the function returns, per 8.5.4p6 in N3290:
(A temporary is created in the return statement and then returned by value. Even if copy elision happens, all other semantics of copying are unchanged.)
Compare to, for example, the temporary initializer_list created here, which is then passed to the ctor and destroyed after the object is initialized, at the same point all other temporary objects in the same full expression (if there were any) would be destroyed:
Instead of manipulating initializer lists, use vector's method to insert N copies: