![](/img/trans.png)
[英]Is a c++11 variadic function template overload with a dependent type ambiguous?
[英]overload variadic function with return type dependent on number of parameters
我正在編寫一個多維數組類,其維數直到運行時才知道。
我已經到達下標運算符,並且想要復制多維本機數組的行為,以便:
返回類型是否可能取決於傳遞給函數的參數數量與直到運行時才知道的值(維數)之間的關系?
其他資訊:
要求,
與標准(1.3.11)相矛盾-方法或運算符不能在返回類型上重載。 因此,從本質上講,您不可能擁有以下簡單的東西:
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) {...}
};
如注釋中所述,您可以返回boost::variant
或您自己的對象。 當然,變體是更好的主意。 您自己的對象的優點是您可以直接控制轉換,但是我不認為這是一個特別好的主意:
class Result;
...
struct MyArrray {
const Result& operator[] (const MyIndex& x) {...}
const Result& operator[] (int, int, int) {...}
然后為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 */ }
};
您已經可以注意到,這很快就變成了泥潭。 這將很難維護,難以推理,並且您的代碼對讀者或審閱者而言也不會明確。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.