(注意:这个问题是不必指定元素的数量,仍然允许直接初始化嵌套类型.)
这个问题讨论了C数组的用途int arr[20];.在他的回答中,@ James Kanze展示了C阵列的最后一个据点,它具有独特的初始化特性:
int arr[] = { 1, 3, 3, 7, 0, 4, 2, 0, 3, 1, 4, 1, 5, 9 };
Run Code Online (Sandbox Code Playgroud)
我们没有必要指定元素的数量,万岁!现在遍历它与C++ 11的功能std::begin和std::end从<iterator>(或您自己的变体),你永远需要甚至认为它的大小.
现在,有没有(可能是TMP)方法实现同样的目标std::array?使用宏可以使它看起来更好.:)
??? std_array = { "here", "be", "elements" };
Run Code Online (Sandbox Code Playgroud)
编辑:中间版本,从各种答案编译,如下所示:
#include <array>
#include <utility>
template<class T, class... Tail, class Elem = typename std::decay<T>::type>
std::array<Elem,1+sizeof...(Tail)> make_array(T&& head, Tail&&... values)
{
return { std::forward<T>(head), std::forward<Tail>(values)... };
}
// in code …Run Code Online (Sandbox Code Playgroud) 如果我们有带有通用引用参数的构造函数,如何声明复制构造函数呢?
http://coliru.stacked-crooked.com/a/4e0355d60297db57
struct Record{
template<class ...Refs>
explicit Record(Refs&&... refs){
cout << "param ctr" << endl;
}
Record(const Record& other){ // never called
cout << "copy ctr" << endl;
}
Record(Record&& other){ // never called
cout << "move ctr" << endl;
}
};
int main() {
Record rec("Hello");
Record rec2(rec); // do "param ctr"
return 0;
}
Run Code Online (Sandbox Code Playgroud)
根据std::tuple http://en.cppreference.com/w/cpp/utility/tuple/tuple [查看案例3和8]的构造函数列表,这个问题在标准库中以某种方式解决了......但我无法通过stl的码.
PS问题与构造函数中的C++通用引用和返回值优化(rvo)有些相关
PPS目前,我刚Record(call_constructor, Refs&&... refs)为真正的EXPLICIT调用添加了额外的第一个参数.而且我可以手动检测我们是否只有一个参数,如果是Record,并且重定向调用复制ctr/param ctr,但....我不敢相信没有标准的方法...