[英]Fold expression as argument of [] operator
I am trying to use a fold expression as the argument of the [] operator. 我试图使用fold表达式作为[]运算符的参数。 Unfortunately, only the first element is correct.
不幸的是,只有第一个元素是正确的。
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
}
However, if I use the same syntax for the argument of a function, it works fine. 但是,如果我对函数的参数使用相同的语法,它可以正常工作。
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? 是什么原因? What would be the solution?
什么是解决方案?
What is the reason?
是什么原因?
The array subscript operator ( operator[]
) must have exactly one argument. 数组下标运算符(
operator[]
)必须只有一个参数。 The first snippet you have shown is invalid for any sizeof...(U) != 1
. 您显示的第一个片段对于任何
sizeof...(U) != 1
都是无效的sizeof...(U) != 1
。
A function template like get
or another operator like operator()
do not have a similar limitation. 像
get
或其他运算operator()
如operator()
类的函数模板没有类似的限制。
What would be the solution?
什么是解决方案?
Do not use operator[]
. 不要使用
operator[]
。
C++ does not have multi-dimensional indexing, and that's "hard-wired" into the syntax - you can't add it by overloading. C ++没有多维索引,并且在语法中“硬连线” - 你不能通过重载来添加它。
The reason that your code compiles at all is that p[a,b]
is equivalent to p[(a,b)]
- that is, it uses the regular comma operator which will compute a
and ignore the result, then produce the value of b
as the index into p
. 您的代码编译在所有的原因是,
p[a,b]
等价于p[(a,b)]
-即,它使用常规的逗号操作符,其将计算a
,并忽略的结果,则产生值b
作为p
的索引。
Thus, your template is never used "variadically", but is essentially the same as 因此,您的模板永远不会“变量”使用,但基本上与之相同
template <class U> T& operator[](U indices)
You need to name the function, or overload an operator that can take more than one parameter, such as operator()
. 您需要为函数命名,或者重载可以使用多个参数的
operator()
,例如operator()
。
As others have mentioned, the subscripting operator operator[]
must accept only a single parameter. 正如其他人所提到的,下标运算符
operator[]
必须只接受一个参数。
See [over.sub] ( emphasis mine ) 见[over.sub]( 强调我的 )
operator[]
shall be a non-static member function with exactly one parameter .operator[]
应该是一个非静态成员函数,只有一个参数 。 It implements the subscripting syntax它实现了下标语法
However, that one parameter doesn't have to be an integer. 但是,该参数不必是整数。
You could still do what you want if you are able to move your values into a std::index_sequence
like so: 如果您能够将值移动到
std::index_sequence
您仍然可以执行您想要的操作:
template<size_t... indices>
T& operator[](std::index_sequence<indices...>){
size_t i=0, k[get_n_dimensions()];
(... , void(k[i++]=indices));
// ...
}
You'd call it like so 你这样称呼它
my_instance[std::make_index_sequence<3>{}]; // passes 0, 1, 2 to the function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.