我正在尝试使用折叠表达式作为 [] 运算符的参数。不幸的是,只有第一个元素是正确的。
template <class ...U> T& operator[](U ...indices){
size_t i=0, k[get_n_dimensions()];
(... , void(k[i++]=indices));
// use k[0], k[1], ...
// only k[0] is correct
}
但是,如果我对函数的参数使用相同的语法,它就可以正常工作。
template <class ...U> T get(U ...indices) const {
size_t i=0, k[get_n_dimensions()];
(... , void(k[i++]=indices));
// k[0], k[1], ... filled correctly
}
这是什么原因?解决方案是什么?
最佳答案
What is the reason?
数组下标运算符 (operator[]
) 必须只有一个参数。您显示的第一个片段对于任何 sizeof...(U) != 1
都是无效的。
get
之类的函数模板或 operator()
之类的其他运算符没有类似的限制。
What would be the solution?
不要使用operator[]
。
关于c++ - 折叠表达式作为 [] 运算符的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54109874/