[英]overload variadic function with return type dependent on number of parameters
I am writing a multi-dimensional array class for which the number of dimensions is not known until runtime. 我正在编写一个多维数组类,其维数直到运行时才知道。
I have gotten to the subscript operator and would like to replicate the behavior of a multidimensional native array so that: 我已经到达下标运算符,并且想要复制多维本机数组的行为,以便:
Is it possible to have the return type depend on the relationship of the number of arguments passed to a function and a value that is not known until runtime (the number of dimensions)? 返回类型是否可能取决于传递给函数的参数数量与直到运行时才知道的值(维数)之间的关系?
Other info: 其他资讯:
The requirements, 要求,
contradict the standard (1.3.11) - a method or an operator cannot be overloaded on return types. 与标准(1.3.11)相矛盾-方法或运算符不能在返回类型上重载。 So essentially it will be impossible for you to have something simple like:
因此,从本质上讲,您不可能拥有以下简单的东西:
class MyIndex; // defined elsewhere
template <typename T> struct MyArray {
const std::array<T>& operator[] (const MyIndex& x) {...}
const T& operator[] (const MyIndex& x) {...}
const T& operator[] (int, int, int) {...}
};
As noted in the comments you could return a boost::variant
or your own object instead. 如注释中所述,您可以返回
boost::variant
或您自己的对象。 The variant is the better idea of course. 当然,变体是更好的主意。 The advantage of your own object is that you'll be able to control the conversions directly, but I don't consider this as a particularly good idea:
您自己的对象的优点是您可以直接控制转换,但是我不认为这是一个特别好的主意:
class Result;
...
struct MyArrray {
const Result& operator[] (const MyIndex& x) {...}
const Result& operator[] (int, int, int) {...}
then add user defined conversions for Result
or possibly separate getter operations to examine and retrieve values: 然后为
Result
添加用户定义的转换,或者可能添加单独的getter操作以检查和检索值:
class Result {
bool hasInt() const;
operator int() const { /* throw if wraps a view else return the value */ }
bool hasView() const;
operator MyArray() const { /* throw if wraps a value else return your array as a view */ }
}; };
You can already note that this quickly becomes a quagmire. 您已经可以注意到,这很快就变成了泥潭。 It'll be hard to maintain, hard to reason about, and your code will not be explicit to the readers or reviewers.
这将很难维护,难以推理,并且您的代码对读者或审阅者而言也不会明确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.